From e5376c6eead8180d9b62729762a5f151e73649bb Mon Sep 17 00:00:00 2001 From: Ali Jaber Date: Sat, 30 May 2026 23:09:57 -0400 Subject: [PATCH 1/9] 141627: Support multiple search instances by prefixing search params with searchInstanceId Adds support for running multiple search components on a single page by prefixing all search-related route and query parameters with a unique search instance id (${searchInstanceId}.${parameterName}). Previously only sort and pagination parameters were scoped; configuration, fixedFilterQuery, scope, query, dsoType, view and filter queries (f.xxx) are now scoped too. --- .../search-configuration.service.spec.ts | 23 +- .../search/search-configuration.service.ts | 227 +++++++++++------- .../shared/search/search-filter.service.ts | 53 +++- .../core/shared/search/search.service.spec.ts | 4 +- src/app/core/shared/search/search.service.ts | 12 +- .../recent-item-list.component.ts | 2 +- .../my-dspace-configuration.service.spec.ts | 14 +- .../my-dspace-configuration.service.ts | 5 + src/app/my-dspace-page/my-dspace.guard.ts | 12 +- .../search-navbar.component.spec.ts | 14 +- .../search-navbar/search-navbar.component.ts | 13 +- ...onfiguration-search-page.component.spec.ts | 4 +- .../configuration-search-page.component.ts | 5 + src/app/search-page/search-page.component.ts | 6 + ...med-configuration-search-page.component.ts | 6 +- ...-relation-external-source-tab.component.ts | 4 +- ...ic-lookup-relation-search-tab.component.ts | 2 +- ...lookup-relation-selection-tab.component.ts | 4 +- .../object-collection.component.ts | 20 +- .../search-form/search-form.component.spec.ts | 28 ++- .../search-form/search-form.component.ts | 25 +- .../search-facet-option.component.ts | 6 +- ...earch-facet-range-option.component.spec.ts | 9 +- .../search-facet-range-option.component.ts | 11 +- .../search-range-filter.component.spec.ts | 7 +- .../search-range-filter.component.ts | 18 +- .../search-results.component.html | 4 +- .../search-results.component.ts | 16 +- .../search-settings.component.ts | 2 +- ...rch-switch-configuration.component.spec.ts | 2 +- .../search-switch-configuration.component.ts | 4 +- .../shared/search/search.component.spec.ts | 23 +- src/app/shared/search/search.component.ts | 20 +- .../shared/search/themed-search.component.ts | 4 +- .../shared/testing/pagination-service.stub.ts | 2 +- .../search-configuration-service.stub.ts | 14 +- 36 files changed, 421 insertions(+), 204 deletions(-) diff --git a/src/app/core/shared/search/search-configuration.service.spec.ts b/src/app/core/shared/search/search-configuration.service.spec.ts index 2cafd67cfeb..e96c67937ef 100644 --- a/src/app/core/shared/search/search-configuration.service.spec.ts +++ b/src/app/core/shared/search/search-configuration.service.spec.ts @@ -90,6 +90,7 @@ describe('SearchConfigurationService', () => { })); service = new SearchConfigurationService(routeService, paginationService as any, activatedRoute as any, linkService, halService, requestService, rdb, environment); + service.searchInstanceId = defaults.pagination.id; }); describe('when the scope is called', () => { @@ -181,7 +182,7 @@ describe('SearchConfigurationService', () => { describe('when subscribeToSearchOptions is called', () => { beforeEach(() => { - (service as any).subscribeToSearchOptions(defaults); + (service as any).subscribeToSearchOptions(defaults.pagination.id, defaults); }); it('should call all getters it needs, but not call any others', () => { expect(service.getCurrentPagination).not.toHaveBeenCalled(); @@ -198,14 +199,14 @@ describe('SearchConfigurationService', () => { beforeEach(() => { (service as any).subscribeToPaginatedSearchOptions(defaults.pagination.id, defaults); }); - it('should call all getters it needs', () => { + it('should call the pagination-specific getters it needs', () => { expect(service.getCurrentPagination).toHaveBeenCalled(); expect(service.getCurrentSort).toHaveBeenCalled(); - expect(service.getCurrentScope).toHaveBeenCalled(); - expect(service.getCurrentConfiguration).toHaveBeenCalled(); - expect(service.getCurrentQuery).toHaveBeenCalled(); - expect(service.getCurrentDSOType).toHaveBeenCalled(); - expect(service.getCurrentFilters).toHaveBeenCalled(); + expect(service.getCurrentScope).not.toHaveBeenCalled(); + expect(service.getCurrentConfiguration).not.toHaveBeenCalled(); + expect(service.getCurrentQuery).not.toHaveBeenCalled(); + expect(service.getCurrentDSOType).not.toHaveBeenCalled(); + expect(service.getCurrentFilters).not.toHaveBeenCalled(); }); }); }); @@ -314,13 +315,13 @@ describe('SearchConfigurationService', () => { it('should return all params except the applied filter', () => { service.unselectAppliedFilterParams(appliedFilter.filter, appliedFilter.value, appliedFilter.operator); - expect(routeService.getParamsExceptValue).toHaveBeenCalledWith('f.author', '1282121b-5394-4689-ab93-78d537764052,authority'); + expect(routeService.getParamsExceptValue).toHaveBeenCalledWith(`${defaults.pagination.id}.f.author`, '1282121b-5394-4689-ab93-78d537764052,authority'); }); it('should be able to remove AppliedFilter without operator', () => { service.unselectAppliedFilterParams('dateIssued.max', '2000'); - expect(routeService.getParamsExceptValue).toHaveBeenCalledWith('f.dateIssued.max', '2000'); + expect(routeService.getParamsExceptValue).toHaveBeenCalledWith(`${defaults.pagination.id}.f.dateIssued.max`, '2000'); }); it('should reset the page to 1', (done: DoneFn) => { @@ -346,13 +347,13 @@ describe('SearchConfigurationService', () => { it('should return all params with the applied filter', () => { service.selectNewAppliedFilterParams(appliedFilter.filter, appliedFilter.value, appliedFilter.operator); - expect(routeService.getParamsWithAdditionalValue).toHaveBeenCalledWith('f.author', '1282121b-5394-4689-ab93-78d537764052,authority'); + expect(routeService.getParamsWithAdditionalValue).toHaveBeenCalledWith(`${defaults.pagination.id}.f.author`, '1282121b-5394-4689-ab93-78d537764052,authority'); }); it('should be able to add AppliedFilter without operator', () => { service.selectNewAppliedFilterParams('dateIssued.max', '2000'); - expect(routeService.getParamsWithAdditionalValue).toHaveBeenCalledWith('f.dateIssued.max', '2000'); + expect(routeService.getParamsWithAdditionalValue).toHaveBeenCalledWith(`${defaults.pagination.id}.f.dateIssued.max`, '2000'); }); it('should reset the page to 1', (done: DoneFn) => { diff --git a/src/app/core/shared/search/search-configuration.service.ts b/src/app/core/shared/search/search-configuration.service.ts index b9e0207cc30..6e6851a2c8a 100644 --- a/src/app/core/shared/search/search-configuration.service.ts +++ b/src/app/core/shared/search/search-configuration.service.ts @@ -85,9 +85,9 @@ export class SearchConfigurationService implements OnDestroy { private facetLinkPathPrefix = 'discover/facets/'; /** - * Default pagination id + * Default search instance id */ - public paginationID = 'spc'; + public searchInstanceId = 'spc'; /** * Emits the current search options @@ -103,7 +103,7 @@ export class SearchConfigurationService implements OnDestroy { * Default pagination settings */ protected defaultPagination = Object.assign(new PaginationComponentOptions(), { - id: this.paginationID, + id: this.searchInstanceId, pageSize: 10, currentPage: 1, }); @@ -158,13 +158,15 @@ export class SearchConfigurationService implements OnDestroy { /** * @returns {Observable} Emits the current configuration string */ - getCurrentConfiguration(defaultConfiguration: string) { + getCurrentConfiguration(defaultConfiguration: string, searchInstanceId = this.searchInstanceId) { return observableCombineLatest([ + this.routeService.getQueryParameterValue(this.getSearchInstanceParam(searchInstanceId, 'configuration')).pipe(startWith(undefined)), + this.routeService.getRouteParameterValue(this.getSearchInstanceParam(searchInstanceId, 'configuration')).pipe(startWith(undefined)), this.routeService.getQueryParameterValue('configuration').pipe(startWith(undefined)), this.routeService.getRouteParameterValue('configuration').pipe(startWith(undefined)), ]).pipe( - map(([queryConfig, routeConfig]) => { - return queryConfig || routeConfig || defaultConfiguration; + map(([instanceQueryConfig, instanceRouteConfig, queryConfig, routeConfig]) => { + return instanceQueryConfig || instanceRouteConfig || queryConfig || routeConfig || defaultConfiguration; }), ); } @@ -172,8 +174,8 @@ export class SearchConfigurationService implements OnDestroy { /** * @returns {Observable} Emits the current scope's identifier */ - getCurrentScope(defaultScope: string) { - return this.routeService.getQueryParameterValue('scope').pipe(map((scope) => { + getCurrentScope(defaultScope: string, searchInstanceId = this.searchInstanceId) { + return this.getCurrentSearchInstanceQueryParam(searchInstanceId, 'scope').pipe(map((scope) => { return scope || defaultScope; })); } @@ -181,17 +183,17 @@ export class SearchConfigurationService implements OnDestroy { /** * @returns {Observable} Emits the current query string */ - getCurrentQuery(defaultQuery: string) { - return this.routeService.getQueryParameterValue('query').pipe(map((query) => { - return query || defaultQuery; + getCurrentQuery(defaultQuery: string, searchInstanceId = this.searchInstanceId) { + return this.getCurrentSearchInstanceQueryParam(searchInstanceId, 'query').pipe(map((query) => { + return hasValue(query) ? query : defaultQuery; })); } /** * @returns {Observable} Emits the current DSpaceObject type as a number */ - getCurrentDSOType(): Observable { - return this.routeService.getQueryParameterValue('dsoType').pipe( + getCurrentDSOType(searchInstanceId = this.searchInstanceId): Observable { + return this.getCurrentSearchInstanceQueryParam(searchInstanceId, 'dsoType').pipe( filter((type) => isNotEmpty(type) && hasValue(DSpaceObjectType[type.toUpperCase()])), map((type) => DSpaceObjectType[type.toUpperCase()])); } @@ -213,20 +215,21 @@ export class SearchConfigurationService implements OnDestroy { /** * @returns {Observable} Emits the current active filters with their values as they are sent to the backend */ - getCurrentFilters(): Observable { - return this.routeService.getQueryParamsWithPrefix('f.').pipe(map((filterParams) => { + getCurrentFilters(searchInstanceId = this.searchInstanceId): Observable { + return this.getCurrentFrontendFilters(searchInstanceId).pipe(map((filterParams) => { if (isNotEmpty(filterParams)) { const filters = []; - Object.keys(filterParams).forEach((key) => { + const backendFilterParams = this.getBackendFilterParams(filterParams, searchInstanceId); + Object.keys(backendFilterParams).forEach((key) => { if (key.endsWith('.min') || key.endsWith('.max')) { const realKey = key.slice(0, -4); if (hasNoValue(filters.find((f) => f.key === realKey))) { - const min = filterParams[realKey + '.min'] ? filterParams[realKey + '.min'][0] : '*'; - const max = filterParams[realKey + '.max'] ? filterParams[realKey + '.max'][0] : '*'; + const min = backendFilterParams[realKey + '.min'] ? backendFilterParams[realKey + '.min'][0] : '*'; + const max = backendFilterParams[realKey + '.max'] ? backendFilterParams[realKey + '.max'][0] : '*'; filters.push(new SearchFilter(realKey, ['[' + min + ' TO ' + max + ']'], 'equals')); } } else { - filters.push(new SearchFilter(key, filterParams[key])); + filters.push(new SearchFilter(key, backendFilterParams[key])); } }); return filters; @@ -238,22 +241,32 @@ export class SearchConfigurationService implements OnDestroy { /** * @returns {Observable} Emits the current fixed filter as a string */ - getCurrentFixedFilter(): Observable { - return this.routeService.getRouteParameterValue('fixedFilterQuery'); + getCurrentFixedFilter(searchInstanceId = this.searchInstanceId): Observable { + return observableCombineLatest([ + this.routeService.getRouteParameterValue(this.getSearchInstanceParam(searchInstanceId, 'fixedFilterQuery')).pipe(startWith(undefined)), + this.routeService.getRouteParameterValue('fixedFilterQuery').pipe(startWith(undefined)), + ]).pipe( + map(([instanceFixedFilter, fixedFilter]) => instanceFixedFilter || fixedFilter), + ); } /** * @returns {Observable} Emits the current active filters with their values as they are displayed in the frontend URL */ - getCurrentFrontendFilters(): Observable { - return this.routeService.getQueryParamsWithPrefix('f.'); + getCurrentFrontendFilters(searchInstanceId = this.searchInstanceId): Observable { + return observableCombineLatest([ + this.routeService.getQueryParamsWithPrefix(this.getSearchInstanceFilterParamPrefix(searchInstanceId)).pipe(startWith({})), + this.routeService.getQueryParamsWithPrefix('f.').pipe(startWith({})), + ]).pipe(map(([instanceFilters, legacyFilters]) => { + return isNotEmpty(instanceFilters) ? instanceFilters : legacyFilters; + })); } /** * @returns {Observable} Emits the current view mode */ - getCurrentViewMode(defaultViewMode: ViewMode) { - return this.routeService.getQueryParameterValue('view').pipe(map((viewMode) => { + getCurrentViewMode(defaultViewMode: ViewMode, searchInstanceId = this.searchInstanceId) { + return this.getCurrentSearchInstanceQueryParam(searchInstanceId, 'view').pipe(map((viewMode) => { return viewMode || defaultViewMode; })); } @@ -296,24 +309,68 @@ export class SearchConfigurationService implements OnDestroy { ); } - setPaginationId(paginationId): void { - if (isNotEmpty(paginationId)) { + setSearchInstanceId(searchInstanceId): void { + if (isNotEmpty(searchInstanceId)) { const currentValue: PaginatedSearchOptions = this.paginatedSearchOptions.getValue(); const updatedValue: PaginatedSearchOptions = Object.assign(new PaginatedSearchOptions({}), currentValue, { pagination: Object.assign({}, currentValue.pagination, { - id: paginationId, + id: searchInstanceId, }), }); - // unsubscribe from subscription related to old pagination id - this.unsubscribeFromSearchOptions(this.paginationID); + // unsubscribe from subscription related to old search instance id + this.unsubscribeFromSearchOptions(this.searchInstanceId); - // change to the new pagination id - this.paginationID = paginationId; + // change to the new search instance id + this.searchInstanceId = searchInstanceId; this.paginatedSearchOptions.next(updatedValue); - this.setSearchSubscription(this.paginationID, this.paginatedSearchOptions.value); + this.setSearchSubscription(this.searchInstanceId, this.paginatedSearchOptions.value); } } + getSearchInstanceParam(searchInstanceId: string, parameterName: string): string { + return `${searchInstanceId}.${parameterName}`; + } + + getCurrentSearchInstanceParam(parameterName: string): string { + return this.getSearchInstanceParam(this.searchInstanceId, parameterName); + } + + getSearchInstanceFilterParam(filterName: string, searchInstanceId = this.searchInstanceId): string { + const filterParamName = filterName.startsWith('f.') ? filterName : `f.${filterName}`; + return this.getSearchInstanceParam(searchInstanceId, filterParamName); + } + + getCurrentSearchInstanceFilterParam(filterName: string): string { + return this.getSearchInstanceFilterParam(filterName, this.searchInstanceId); + } + + getSearchInstanceFilterParamPrefix(searchInstanceId = this.searchInstanceId): string { + return this.getSearchInstanceParam(searchInstanceId, 'f.'); + } + + getCurrentPageParam(): string { + return this.paginationService.getPageParam(this.searchInstanceId); + } + + private getCurrentSearchInstanceQueryParam(searchInstanceId: string, parameterName: string): Observable { + return observableCombineLatest([ + this.routeService.getQueryParameterValue(this.getSearchInstanceParam(searchInstanceId, parameterName)).pipe(startWith(undefined)), + this.routeService.getQueryParameterValue(parameterName).pipe(startWith(undefined)), + ]).pipe( + map(([instanceValue, legacyValue]) => hasValue(instanceValue) ? instanceValue : legacyValue), + ); + } + + private getBackendFilterParams(filterParams: Params, searchInstanceId: string): Params { + const backendFilterParams = {}; + const instancePrefix = `${searchInstanceId}.`; + Object.keys(filterParams).forEach((key) => { + const backendKey = key.startsWith(instancePrefix) ? key.substring(instancePrefix.length) : key; + backendFilterParams[backendKey] = filterParams[key]; + }); + return backendFilterParams; + } + /** * Make sure to unsubscribe from all existing subscription to prevent memory leaks */ @@ -337,17 +394,18 @@ export class SearchConfigurationService implements OnDestroy { const defs = defRD.payload; this.paginatedSearchOptions = new BehaviorSubject(defs); this.searchOptions = new BehaviorSubject(defs); - this.setSearchSubscription(this.paginationID, defs); + this.setSearchSubscription(this.searchInstanceId, defs); }); } - private setSearchSubscription(paginationID: string, defaults: PaginatedSearchOptions) { - this.unsubscribeFromSearchOptions(paginationID); + private setSearchSubscription(searchInstanceId: string, defaults: PaginatedSearchOptions) { + const instanceId = searchInstanceId || defaults.pagination.id; + this.unsubscribeFromSearchOptions(instanceId); const subs = [ - this.subscribeToSearchOptions(defaults), - this.subscribeToPaginatedSearchOptions(paginationID || defaults.pagination.id, defaults), + this.subscribeToSearchOptions(instanceId, defaults), + this.subscribeToPaginatedSearchOptions(instanceId, defaults), ]; - this.subs.set(this.paginationID, subs); + this.subs.set(instanceId, subs); } /** @@ -355,39 +413,38 @@ export class SearchConfigurationService implements OnDestroy { * @param {SearchOptions} defaults Default values for when no parameters are available * @returns {Subscription} The subscription to unsubscribe from */ - private subscribeToSearchOptions(defaults: SearchOptions): Subscription { + private subscribeToSearchOptions(searchInstanceId: string, defaults: SearchOptions): Subscription { return observableMerge( - this.getConfigurationPart(defaults.configuration), - this.getScopePart(defaults.scope), - this.getQueryPart(defaults.query), - this.getDSOTypePart(), - this.getFiltersPart(), - this.getFixedFilterPart(), - this.getViewModePart(defaults.view), + this.getConfigurationPart(searchInstanceId, defaults.configuration), + this.getScopePart(searchInstanceId, defaults.scope), + this.getQueryPart(searchInstanceId, defaults.query), + this.getDSOTypePart(searchInstanceId), + this.getFiltersPart(searchInstanceId), + this.getFixedFilterPart(searchInstanceId), + this.getViewModePart(searchInstanceId, defaults.view), ).subscribe((update) => { const currentValue: SearchOptions = this.searchOptions.getValue(); - const updatedValue: SearchOptions = Object.assign(new PaginatedSearchOptions({}), currentValue, update); + const updatedValue: SearchOptions = Object.assign(new SearchOptions({}), currentValue, update); this.searchOptions.next(updatedValue); }); } /** * Sets up a subscription to all necessary parameters to make sure the paginatedSearchOptions emits a new value every time they update - * @param {string} paginationId The pagination ID + * @param {string} searchInstanceId The search instance id * @param {PaginatedSearchOptions} defaults Default values for when no parameters are available * @returns {Subscription} The subscription to unsubscribe from */ - private subscribeToPaginatedSearchOptions(paginationId: string, defaults: PaginatedSearchOptions): Subscription { + private subscribeToPaginatedSearchOptions(searchInstanceId: string, defaults: PaginatedSearchOptions): Subscription { return observableMerge( - this.getConfigurationPart(defaults.configuration), - this.getPaginationPart(paginationId, defaults.pagination), - this.getSortPart(paginationId, defaults.sort), - this.getScopePart(defaults.scope), - this.getQueryPart(defaults.query), - this.getDSOTypePart(), - this.getFiltersPart(), - this.getFixedFilterPart(), - this.getViewModePart(defaults.view), + this.searchOptions.pipe(map((searchOptions: any) => { + const update = Object.assign({}, searchOptions); + delete update.pagination; + delete update.sort; + return update; + })), + this.getPaginationPart(searchInstanceId, defaults.pagination), + this.getSortPart(searchInstanceId, defaults.sort), ).subscribe((update) => { const currentValue: PaginatedSearchOptions = this.paginatedSearchOptions.getValue(); const updatedValue: PaginatedSearchOptions = Object.assign(new PaginatedSearchOptions({}), currentValue, update); @@ -396,23 +453,23 @@ export class SearchConfigurationService implements OnDestroy { } /** - * Unsubscribe from all subscriptions related to the given paginationID - * @param paginationId The pagination id + * Unsubscribe from all subscriptions related to the given search instance id + * @param searchInstanceId The search instance id */ - private unsubscribeFromSearchOptions(paginationId: string): void { - if (this.subs.has(this.paginationID)) { - this.subs.get(this.paginationID) + private unsubscribeFromSearchOptions(searchInstanceId: string): void { + if (this.subs.has(searchInstanceId)) { + this.subs.get(searchInstanceId) .filter((sub) => hasValue(sub)) .forEach((sub) => sub.unsubscribe()); - this.subs.delete(paginationId); + this.subs.delete(searchInstanceId); } } /** * @returns {Observable} Emits the current configuration settings as a partial SearchOptions object */ - private getConfigurationPart(defaultConfiguration: string): Observable { - return this.getCurrentConfiguration(defaultConfiguration).pipe(map((configuration) => { + private getConfigurationPart(searchInstanceId: string, defaultConfiguration: string): Observable { + return this.getCurrentConfiguration(defaultConfiguration, searchInstanceId).pipe(map((configuration) => { return { configuration }; })); } @@ -420,8 +477,8 @@ export class SearchConfigurationService implements OnDestroy { /** * @returns {Observable} Emits the current scope's identifier */ - private getScopePart(defaultScope: string): Observable { - return this.getCurrentScope(defaultScope).pipe(map((scope) => { + private getScopePart(searchInstanceId: string, defaultScope: string): Observable { + return this.getCurrentScope(defaultScope, searchInstanceId).pipe(map((scope) => { return { scope }; })); } @@ -429,8 +486,8 @@ export class SearchConfigurationService implements OnDestroy { /** * @returns {Observable} Emits the current query string as a partial SearchOptions object */ - private getQueryPart(defaultQuery: string): Observable { - return this.getCurrentQuery(defaultQuery).pipe(map((query) => { + private getQueryPart(searchInstanceId: string, defaultQuery: string): Observable { + return this.getCurrentQuery(defaultQuery, searchInstanceId).pipe(map((query) => { return { query }; })); } @@ -438,8 +495,8 @@ export class SearchConfigurationService implements OnDestroy { /** * @returns {Observable} Emits the current query string as a partial SearchOptions object */ - private getDSOTypePart(): Observable { - return this.getCurrentDSOType().pipe(map((dsoType) => { + private getDSOTypePart(searchInstanceId: string): Observable { + return this.getCurrentDSOType(searchInstanceId).pipe(map((dsoType) => { return { dsoType }; })); } @@ -465,8 +522,8 @@ export class SearchConfigurationService implements OnDestroy { /** * @returns {Observable} Emits the current active filters as a partial SearchOptions object */ - private getFiltersPart(): Observable { - return this.getCurrentFilters().pipe(map((filters) => { + private getFiltersPart(searchInstanceId: string): Observable { + return this.getCurrentFilters(searchInstanceId).pipe(map((filters) => { return { filters }; })); } @@ -474,8 +531,8 @@ export class SearchConfigurationService implements OnDestroy { /** * @returns {Observable} Emits the current fixed filter as a partial SearchOptions object */ - private getFixedFilterPart(): Observable { - return this.getCurrentFixedFilter().pipe( + private getFixedFilterPart(searchInstanceId: string): Observable { + return this.getCurrentFixedFilter(searchInstanceId).pipe( isNotEmptyOperator(), map((fixedFilter) => { return { fixedFilter }; @@ -579,9 +636,11 @@ export class SearchConfigurationService implements OnDestroy { * @param operator The {@link AppliedFilter}'s optional operator */ unselectAppliedFilterParams(filterName: string, value: string, operator?: string): Observable { - return this.routeService.getParamsExceptValue(`f.${filterName}`, hasValue(operator) ? addOperatorToFilterValue(value, operator) : value).pipe( + const filterParam: string = this.getCurrentSearchInstanceFilterParam(filterName); + return this.routeService.getParamsExceptValue(filterParam, hasValue(operator) ? addOperatorToFilterValue(value, operator) : value).pipe( map((params: Params) => Object.assign(params, { - [this.paginationService.getPageParam(this.paginationID)]: 1, + [`f.${filterName}`]: null, + [this.paginationService.getPageParam(this.searchInstanceId)]: 1, })), ); } @@ -594,9 +653,11 @@ export class SearchConfigurationService implements OnDestroy { * @param operator The {@link AppliedFilter}'s optional operator */ selectNewAppliedFilterParams(filterName: string, value: string, operator?: string): Observable { - return this.routeService.getParamsWithAdditionalValue(`f.${filterName}`, hasValue(operator) ? addOperatorToFilterValue(value, operator) : value).pipe( + const filterParam: string = this.getCurrentSearchInstanceFilterParam(filterName); + return this.routeService.getParamsWithAdditionalValue(filterParam, hasValue(operator) ? addOperatorToFilterValue(value, operator) : value).pipe( map((params: Params) => Object.assign(params, { - [this.paginationService.getPageParam(this.paginationID)]: 1, + [`f.${filterName}`]: null, + [this.paginationService.getPageParam(this.searchInstanceId)]: 1, })), ); } @@ -604,8 +665,8 @@ export class SearchConfigurationService implements OnDestroy { /** * @returns {Observable} Emits the current view mode as a partial SearchOptions object */ - private getViewModePart(defaultViewMode: ViewMode): Observable { - return this.getCurrentViewMode(defaultViewMode).pipe(map((view) => { + private getViewModePart(searchInstanceId: string, defaultViewMode: ViewMode): Observable { + return this.getCurrentViewMode(defaultViewMode, searchInstanceId).pipe(map((view) => { return { view }; })); } diff --git a/src/app/core/shared/search/search-filter.service.ts b/src/app/core/shared/search/search-filter.service.ts index ddf19632c54..506f76fd264 100644 --- a/src/app/core/shared/search/search-filter.service.ts +++ b/src/app/core/shared/search/search-filter.service.ts @@ -1,5 +1,4 @@ import { Injectable } from '@angular/core'; -import { Params } from '@angular/router'; import { createSelector, MemoizedSelector, @@ -75,7 +74,14 @@ export class SearchFilterService { * @param {string} filterValue The value for which to search * @returns {Observable} Emit true when the filter is active with the given value */ - isFilterActiveWithValue(paramName: string, filterValue: string): Observable { + isFilterActiveWithValue(paramName: string, filterValue: string, searchInstanceId?: string): Observable { + if (hasValue(searchInstanceId)) { + return observableCombineLatest( + this.routeService.hasQueryParamWithValue(this.getSearchInstanceParam(searchInstanceId, paramName), filterValue), + this.routeService.getQueryParamsWithPrefix(this.getSearchInstanceParam(searchInstanceId, 'f.')), + this.routeService.hasQueryParamWithValue(paramName, filterValue), + ).pipe(map(([instanceActive, instanceFilters, legacyActive]) => instanceActive || (!isNotEmpty(instanceFilters) && legacyActive))); + } return this.routeService.hasQueryParamWithValue(paramName, filterValue); } @@ -84,7 +90,14 @@ export class SearchFilterService { * @param {string} paramName The parameter name of the filter's configuration for which to search * @returns {Observable} Emit true when the filter is active with any value */ - isFilterActive(paramName: string): Observable { + isFilterActive(paramName: string, searchInstanceId?: string): Observable { + if (hasValue(searchInstanceId)) { + return observableCombineLatest( + this.routeService.hasQueryParam(this.getSearchInstanceParam(searchInstanceId, paramName)), + this.routeService.getQueryParamsWithPrefix(this.getSearchInstanceParam(searchInstanceId, 'f.')), + this.routeService.hasQueryParam(paramName), + ).pipe(map(([instanceActive, instanceFilters, legacyActive]) => instanceActive || (!isNotEmpty(instanceFilters) && legacyActive))); + } return this.routeService.hasQueryParam(paramName); } @@ -92,16 +105,16 @@ export class SearchFilterService { * Fetch the current active scope from the query parameters * @returns {Observable} */ - getCurrentScope(): Observable { - return this.routeService.getQueryParameterValue('scope'); + getCurrentScope(searchInstanceId?: string) { + return this.getCurrentSearchInstanceQueryParam(searchInstanceId, 'scope'); } /** * Fetch the current query from the query parameters * @returns {Observable} */ - getCurrentQuery(): Observable { - return this.routeService.getQueryParameterValue('query'); + getCurrentQuery(searchInstanceId?: string) { + return this.getCurrentSearchInstanceQueryParam(searchInstanceId, 'query'); } /** @@ -142,7 +155,13 @@ export class SearchFilterService { * Fetch the current active filters from the query parameters * @returns {Observable} */ - getCurrentFilters(): Observable { + getCurrentFilters(searchInstanceId?: string) { + if (hasValue(searchInstanceId)) { + return observableCombineLatest( + this.routeService.getQueryParamsWithPrefix(this.getSearchInstanceParam(searchInstanceId, 'f.')), + this.routeService.getQueryParamsWithPrefix('f.'), + ).pipe(map(([instanceFilters, legacyFilters]) => isNotEmpty(instanceFilters) ? instanceFilters : legacyFilters)); + } return this.routeService.getQueryParamsWithPrefix('f.'); } @@ -150,8 +169,8 @@ export class SearchFilterService { * Fetch the current view from the query parameters * @returns {Observable} */ - getCurrentView(): Observable { - return this.routeService.getQueryParameterValue('view'); + getCurrentView(searchInstanceId?: string) { + return this.getCurrentSearchInstanceQueryParam(searchInstanceId, 'view'); } /** @@ -190,6 +209,20 @@ export class SearchFilterService { return `${new EmphasizePipe().transform(facet.value, query)} (${facet.count})`; } + private getSearchInstanceParam(searchInstanceId: string, parameterName: string): string { + return `${searchInstanceId}.${parameterName}`; + } + + private getCurrentSearchInstanceQueryParam(searchInstanceId: string | undefined, parameterName: string): Observable { + if (hasValue(searchInstanceId)) { + return observableCombineLatest( + this.routeService.getQueryParameterValue(this.getSearchInstanceParam(searchInstanceId, parameterName)), + this.routeService.getQueryParameterValue(parameterName), + ).pipe(map(([instanceValue, legacyValue]) => hasValue(instanceValue) ? instanceValue : legacyValue)); + } + return this.routeService.getQueryParameterValue(parameterName); + } + /** * Checks if the state of a given filter is currently collapsed or not * @param {string} filterName The filtername for which the collapsed state is checked diff --git a/src/app/core/shared/search/search.service.spec.ts b/src/app/core/shared/search/search.service.spec.ts index b3bd6c7ba3f..f595b8cee16 100644 --- a/src/app/core/shared/search/search.service.spec.ts +++ b/src/app/core/shared/search/search.service.spec.ts @@ -98,13 +98,13 @@ describe('SearchService', () => { it('should call the navigate method on the Router with view mode list parameter as a parameter when setViewMode is called', () => { service.setViewMode(ViewMode.ListElement); - expect(paginationService.updateRouteWithUrl).toHaveBeenCalledWith('test-id', ['/search'], { page: 1 }, { view: ViewMode.ListElement }); + expect(paginationService.updateRouteWithUrl).toHaveBeenCalledWith('test-id', ['/search'], { page: 1 }, { 'test-id.view': ViewMode.ListElement }); }); it('should call the navigate method on the Router with view mode grid parameter as a parameter when setViewMode is called', () => { service.setViewMode(ViewMode.GridElement); - expect(paginationService.updateRouteWithUrl).toHaveBeenCalledWith('test-id', ['/search'], { page: 1 }, { view: ViewMode.GridElement }); + expect(paginationService.updateRouteWithUrl).toHaveBeenCalledWith('test-id', ['/search'], { page: 1 }, { 'test-id.view': ViewMode.GridElement }); }); }); diff --git a/src/app/core/shared/search/search.service.ts b/src/app/core/shared/search/search.service.ts index c694c6ce24d..50d2dae3b90 100644 --- a/src/app/core/shared/search/search.service.ts +++ b/src/app/core/shared/search/search.service.ts @@ -342,8 +342,10 @@ export class SearchService { */ getViewMode(): Observable { return this.routeService.getQueryParamMap().pipe(map((params) => { - if (isNotEmpty(params.get('view')) && hasValue(params.get('view'))) { - return params.get('view'); + const viewParam = this.searchConfigurationService.getCurrentSearchInstanceParam('view'); + const view = hasValue(params.get(viewParam)) ? params.get(viewParam) : params.get('view'); + if (isNotEmpty(view) && hasValue(view)) { + return view; } else { return ViewMode.ListElement; } @@ -356,16 +358,16 @@ export class SearchService { * @param {string[]} searchLinkParts */ setViewMode(viewMode: ViewMode, searchLinkParts?: string[]) { - this.paginationService.getCurrentPagination(this.searchConfigurationService.paginationID, new PaginationComponentOptions()).pipe(take(1)) + this.paginationService.getCurrentPagination(this.searchConfigurationService.searchInstanceId, new PaginationComponentOptions()).pipe(take(1)) .subscribe((config) => { let pageParams = { page: 1 }; - const queryParams = { view: viewMode }; + const queryParams = { [this.searchConfigurationService.getCurrentSearchInstanceParam('view')]: viewMode }; if (viewMode === ViewMode.DetailedListElement) { pageParams = Object.assign(pageParams, { pageSize: 1 }); } else if (config.pageSize === 1) { pageParams = Object.assign(pageParams, { pageSize: 10 }); } - this.paginationService.updateRouteWithUrl(this.searchConfigurationService.paginationID, hasValue(searchLinkParts) ? searchLinkParts : [this.getSearchLink()], pageParams, queryParams); + this.paginationService.updateRouteWithUrl(this.searchConfigurationService.searchInstanceId, hasValue(searchLinkParts) ? searchLinkParts : [this.getSearchLink()], pageParams, queryParams); }); } diff --git a/src/app/home-page/recent-item-list/recent-item-list.component.ts b/src/app/home-page/recent-item-list/recent-item-list.component.ts index 1883a959b18..5e692e10eff 100644 --- a/src/app/home-page/recent-item-list/recent-item-list.component.ts +++ b/src/app/home-page/recent-item-list/recent-item-list.component.ts @@ -128,7 +128,7 @@ export class RecentItemListComponent implements OnInit, OnDestroy { } onLoadMore(): void { - this.paginationService.updateRouteWithUrl(this.searchConfigurationService.paginationID, ['search'], { + this.paginationService.updateRouteWithUrl(this.searchConfigurationService.searchInstanceId, ['search'], { sortField: environment.homePage.recentSubmissions.sortField, sortDirection: 'DESC' as SortDirection, page: 1, diff --git a/src/app/my-dspace-page/my-dspace-configuration.service.spec.ts b/src/app/my-dspace-page/my-dspace-configuration.service.spec.ts index 098e1f51cc6..0d44fbcecee 100644 --- a/src/app/my-dspace-page/my-dspace-configuration.service.spec.ts +++ b/src/app/my-dspace-page/my-dspace-configuration.service.spec.ts @@ -151,7 +151,7 @@ describe('MyDSpaceConfigurationService', () => { describe('when subscribeToSearchOptions is called', () => { beforeEach(() => { - (service as any).subscribeToSearchOptions(defaults); + (service as any).subscribeToSearchOptions(defaults.pagination.id, defaults); }); it('should call all getters it needs, but not call any others', () => { expect(service.getCurrentPagination).not.toHaveBeenCalled(); @@ -168,14 +168,14 @@ describe('MyDSpaceConfigurationService', () => { beforeEach(() => { (service as any).subscribeToPaginatedSearchOptions('id', defaults); }); - it('should call all getters it needs', () => { + it('should call the pagination-specific getters it needs', () => { expect(service.getCurrentPagination).toHaveBeenCalled(); expect(service.getCurrentSort).toHaveBeenCalled(); - expect(service.getCurrentScope).toHaveBeenCalled(); - expect(service.getCurrentConfiguration).toHaveBeenCalled(); - expect(service.getCurrentQuery).toHaveBeenCalled(); - expect(service.getCurrentDSOType).toHaveBeenCalled(); - expect(service.getCurrentFilters).toHaveBeenCalled(); + expect(service.getCurrentScope).not.toHaveBeenCalled(); + expect(service.getCurrentConfiguration).not.toHaveBeenCalled(); + expect(service.getCurrentQuery).not.toHaveBeenCalled(); + expect(service.getCurrentDSOType).not.toHaveBeenCalled(); + expect(service.getCurrentFilters).not.toHaveBeenCalled(); }); }); }); diff --git a/src/app/my-dspace-page/my-dspace-configuration.service.ts b/src/app/my-dspace-page/my-dspace-configuration.service.ts index 9a7f3764046..f958af9297a 100644 --- a/src/app/my-dspace-page/my-dspace-configuration.service.ts +++ b/src/app/my-dspace-page/my-dspace-configuration.service.ts @@ -47,6 +47,11 @@ export const SEARCH_CONFIG_SERVICE: InjectionToken = */ @Injectable({ providedIn: 'root' }) export class MyDSpaceConfigurationService extends SearchConfigurationService { + /** + * Search instance id used for the MyDSpace search component. + */ + public searchInstanceId = 'mydspace-page'; + /** * Default pagination settings */ diff --git a/src/app/my-dspace-page/my-dspace.guard.ts b/src/app/my-dspace-page/my-dspace.guard.ts index c174c9594ee..3f1f24dabaf 100644 --- a/src/app/my-dspace-page/my-dspace.guard.ts +++ b/src/app/my-dspace-page/my-dspace.guard.ts @@ -26,9 +26,11 @@ export const myDSpaceGuard: CanActivateFn = ( configurationService: MyDSpaceConfigurationService = inject(MyDSpaceConfigurationService), router: Router = inject(Router), ): Observable => { + const configurationParam = configurationService.getCurrentSearchInstanceParam('configuration'); + const configuration = route.queryParamMap.get(configurationParam) || route.queryParamMap.get('configuration'); return configurationService.getAvailableConfigurationTypes().pipe( first(), - map((configurationList) => validateConfigurationParam(router, route.queryParamMap.get('configuration'), configurationList))); + map((configurationList) => validateConfigurationParam(router, configurationService, configuration, configurationList))); }; /** @@ -36,18 +38,22 @@ export const myDSpaceGuard: CanActivateFn = ( * * @param router * the service router + * @param configurationService + * the MyDSpace configuration service * @param configuration * the configuration to validate * @param configurationList * the list of available configuration * */ -function validateConfigurationParam(router: Router, configuration: string, configurationList: MyDSpaceConfigurationValueType[]): boolean { +function validateConfigurationParam(router: Router, configurationService: MyDSpaceConfigurationService, configuration: string, configurationList: MyDSpaceConfigurationValueType[]): boolean { const configurationDefault: string = configurationList[0]; if (isEmpty(configuration) || !configurationList.includes(configuration as MyDSpaceConfigurationValueType)) { // If configuration param is empty or is not included in available configurations redirect to a default configuration value const navigationExtras: NavigationExtras = { - queryParams: { configuration: configurationDefault }, + queryParams: { + [configurationService.getCurrentSearchInstanceParam('configuration')]: configurationDefault, + }, }; router.navigate([MYDSPACE_ROUTE], navigationExtras); diff --git a/src/app/search-navbar/search-navbar.component.spec.ts b/src/app/search-navbar/search-navbar.component.spec.ts index 3d383cbcef3..2792330d0ac 100644 --- a/src/app/search-navbar/search-navbar.component.spec.ts +++ b/src/app/search-navbar/search-navbar.component.spec.ts @@ -21,7 +21,9 @@ import { TranslateModule, } from '@ngx-translate/core'; +import { PaginationService } from '../core/pagination/pagination.service'; import { SearchService } from '../core/shared/search/search.service'; +import { SearchConfigurationService } from '../core/shared/search/search-configuration.service'; import { TranslateLoaderMock } from '../shared/mocks/translate-loader.mock'; import { SearchNavbarComponent } from './search-navbar.component'; @@ -54,6 +56,14 @@ describe('SearchNavbarComponent', () => { ], providers: [ { provide: SearchService, useValue: mockSearchService }, + { provide: PaginationService, useValue: { getPageParam: (id: string) => `${id}.page` } }, + { + provide: SearchConfigurationService, + useValue: { + searchInstanceId: 'spc', + getCurrentSearchInstanceParam: (param: string) => `spc.${param}`, + }, + }, ], }) .compileComponents(); @@ -100,7 +110,7 @@ describe('SearchNavbarComponent', () => { fixture.detectChanges(); })); it('to search page with empty query', () => { - const extras: NavigationExtras = { queryParams: { query: '' } }; + const extras: NavigationExtras = { queryParams: { 'spc.query': '', 'spc.page': 1 } }; expect(component.onSubmit).toHaveBeenCalledWith({ query: '' }); expect(router.navigate).toHaveBeenCalledWith(['search'], extras); }); @@ -125,7 +135,7 @@ describe('SearchNavbarComponent', () => { fixture.detectChanges(); })); it('to search page with query', async () => { - const extras: NavigationExtras = { queryParams: { query: 'test' } }; + const extras: NavigationExtras = { queryParams: { 'spc.query': 'test', 'spc.page': 1 } }; expect(component.onSubmit).toHaveBeenCalledWith({ query: 'test' }); expect(router.navigate).toHaveBeenCalledWith(['search'], extras); diff --git a/src/app/search-navbar/search-navbar.component.ts b/src/app/search-navbar/search-navbar.component.ts index ca90d477bf7..cb6d86cedb0 100644 --- a/src/app/search-navbar/search-navbar.component.ts +++ b/src/app/search-navbar/search-navbar.component.ts @@ -11,7 +11,9 @@ import { import { Router } from '@angular/router'; import { TranslateModule } from '@ngx-translate/core'; +import { PaginationService } from '../core/pagination/pagination.service'; import { SearchService } from '../core/shared/search/search.service'; +import { SearchConfigurationService } from '../core/shared/search/search-configuration.service'; import { expandSearchInput } from '../shared/animations/slide'; import { BrowserOnlyPipe } from '../shared/utils/browser-only.pipe'; import { ClickOutsideDirective } from '../shared/utils/click-outside.directive'; @@ -44,7 +46,11 @@ export class SearchNavbarComponent { // Search input field @ViewChild('searchInput') searchField: ElementRef; - constructor(private formBuilder: UntypedFormBuilder, private router: Router, private searchService: SearchService) { + constructor(private formBuilder: UntypedFormBuilder, + private router: Router, + private searchService: SearchService, + private searchConfigurationService: SearchConfigurationService, + private paginationService: PaginationService) { this.searchForm = this.formBuilder.group(({ query: '', })); @@ -81,7 +87,10 @@ export class SearchNavbarComponent { */ onSubmit(data: any) { this.collapse(); - const queryParams = Object.assign({}, data); + const queryParams = { + [this.searchConfigurationService.getCurrentSearchInstanceParam('query')]: data.query, + [this.paginationService.getPageParam(this.searchConfigurationService.searchInstanceId)]: 1, + }; const linkToNavigateTo = [this.searchService.getSearchLink().replace('/', '')]; this.searchForm.reset(); diff --git a/src/app/search-page/configuration-search-page.component.spec.ts b/src/app/search-page/configuration-search-page.component.spec.ts index f3931a2016f..68e0740ac06 100644 --- a/src/app/search-page/configuration-search-page.component.spec.ts +++ b/src/app/search-page/configuration-search-page.component.spec.ts @@ -65,8 +65,8 @@ describe('ConfigurationSearchPageComponent', () => { expect(comp.configuration).toBe(CONFIGURATION); expect(comp.fixedFilterQuery).toBe(QUERY); - expect(routeService.setParameter).toHaveBeenCalledWith('configuration', CONFIGURATION); - expect(routeService.setParameter).toHaveBeenCalledWith('fixedFilterQuery', QUERY); + expect(routeService.setParameter).toHaveBeenCalledWith('search-test-page-id.configuration', CONFIGURATION); + expect(routeService.setParameter).toHaveBeenCalledWith('search-test-page-id.fixedFilterQuery', QUERY); }); }); diff --git a/src/app/search-page/configuration-search-page.component.ts b/src/app/search-page/configuration-search-page.component.ts index 5458d9a1b4e..09eea9a2177 100644 --- a/src/app/search-page/configuration-search-page.component.ts +++ b/src/app/search-page/configuration-search-page.component.ts @@ -44,6 +44,11 @@ import { ViewModeSwitchComponent } from '../shared/view-mode-switch/view-mode-sw provide: SEARCH_CONFIG_SERVICE, useClass: SearchConfigurationService, }, + { + provide: SearchConfigurationService, + useExisting: SEARCH_CONFIG_SERVICE, + }, + SearchService, ], standalone: true, imports: [ diff --git a/src/app/search-page/search-page.component.ts b/src/app/search-page/search-page.component.ts index f9ae3c60c95..5a817472111 100644 --- a/src/app/search-page/search-page.component.ts +++ b/src/app/search-page/search-page.component.ts @@ -1,5 +1,6 @@ import { Component } from '@angular/core'; +import { SearchService } from '../core/shared/search/search.service'; import { SearchConfigurationService } from '../core/shared/search/search-configuration.service'; import { SEARCH_CONFIG_SERVICE } from '../my-dspace-page/my-dspace-configuration.service'; import { ThemedSearchComponent } from '../shared/search/themed-search.component'; @@ -12,6 +13,11 @@ import { ThemedSearchComponent } from '../shared/search/themed-search.component' provide: SEARCH_CONFIG_SERVICE, useClass: SearchConfigurationService, }, + { + provide: SearchConfigurationService, + useExisting: SEARCH_CONFIG_SERVICE, + }, + SearchService, ], standalone: true, imports: [ diff --git a/src/app/search-page/themed-configuration-search-page.component.ts b/src/app/search-page/themed-configuration-search-page.component.ts index a455ddf5fe8..c99884c957f 100644 --- a/src/app/search-page/themed-configuration-search-page.component.ts +++ b/src/app/search-page/themed-configuration-search-page.component.ts @@ -63,9 +63,9 @@ export class ThemedConfigurationSearchPageComponent extends ThemedComponent; + private viewMode$: BehaviorSubject = new BehaviorSubject(undefined); + /** * The available view modes */ @@ -228,10 +241,9 @@ export class ObjectCollectionComponent implements OnInit { } ngOnInit(): void { - this.currentMode$ = this.route - .queryParams + this.currentMode$ = observableCombineLatest([this.route.queryParams, this.viewMode$]) .pipe( - map((params) => isEmpty(params?.view) ? ViewMode.ListElement : params.view), + map(([params, viewMode]) => viewMode || (isEmpty(params?.view) ? ViewMode.ListElement : params.view)), distinctUntilChanged(), ); if (isPlatformBrowser(this.platformId)) { diff --git a/src/app/shared/search-form/search-form.component.spec.ts b/src/app/shared/search-form/search-form.component.spec.ts index a1c02f3a8e9..81c7950175c 100644 --- a/src/app/shared/search-form/search-form.component.spec.ts +++ b/src/app/shared/search-form/search-form.component.spec.ts @@ -35,8 +35,10 @@ describe('SearchFormComponent', () => { const searchService = new SearchServiceStub(); let searchFilterService: SearchFilterServiceStub; const paginationService = new PaginationServiceStub(); - const searchConfigService = { paginationID: 'test-id' }; - const firstPage = { 'spc.page': 1 }; + const searchConfigService = { + searchInstanceId: 'test-id', + getCurrentSearchInstanceParam: (param: string) => `test-id.${param}`, + }; const dspaceObjectService = { findById: () => createSuccessfulRemoteDataObject$(undefined), }; @@ -111,11 +113,17 @@ describe('SearchFormComponent', () => { const scope = 'MCU'; let searchQuery = {}; - it('should navigate to the search first page even when no parameters are provided', () => { + beforeEach(() => { + searchQuery = {}; + router.navigate.calls.reset(); + }); + + it('should navigate to the search page even when no parameters are provided', () => { + const expectedQueryParams = { 'test-id.page': 1 }; comp.updateSearch(searchQuery); expect(router.navigate).toHaveBeenCalledWith(comp.getSearchLinkParts(), { - queryParams: { ...searchQuery, ...firstPage }, + queryParams: expectedQueryParams, queryParamsHandling: 'merge', }); }); @@ -124,11 +132,15 @@ describe('SearchFormComponent', () => { searchQuery = { query: query, }; + const expectedQueryParams = { + 'test-id.page': 1, + 'test-id.query': query, + }; comp.updateSearch(searchQuery); expect(router.navigate).toHaveBeenCalledWith(comp.getSearchLinkParts(), { - queryParams: { ...searchQuery, ...firstPage }, + queryParams: expectedQueryParams, queryParamsHandling: 'merge', }); }); @@ -137,11 +149,15 @@ describe('SearchFormComponent', () => { searchQuery = { scope: scope, }; + const expectedQueryParams = { + 'test-id.page': 1, + 'test-id.scope': scope, + }; comp.updateSearch(searchQuery); expect(router.navigate).toHaveBeenCalledWith(comp.getSearchLinkParts(), { - queryParams: { ...searchQuery, ...firstPage }, + queryParams: expectedQueryParams, queryParamsHandling: 'merge', }); }); diff --git a/src/app/shared/search-form/search-form.component.ts b/src/app/shared/search-form/search-form.component.ts index 700e3eb691f..96b51ed94fc 100644 --- a/src/app/shared/search-form/search-form.component.ts +++ b/src/app/shared/search-form/search-form.component.ts @@ -7,7 +7,10 @@ import { Output, } from '@angular/core'; import { FormsModule } from '@angular/forms'; -import { Router } from '@angular/router'; +import { + Params, + Router, +} from '@angular/router'; import { NgbModal, NgbTooltipModule, @@ -147,17 +150,15 @@ export class SearchFormComponent implements OnChanges { * @param data Updated parameters */ updateSearch(data: any) { - const goToFirstPage = { 'spc.page': 1 }; - - const queryParams = Object.assign( - { - ...goToFirstPage, - }, - data, - ); - if (hasValue(data.scope) && this.hideScopeInUrl) { - delete queryParams.scope; - } + const queryParams: Params = { + [this.paginationService.getPageParam(this.searchConfig.searchInstanceId)]: 1, + }; + Object.keys(data).forEach((key) => { + if (key === 'scope' && hasValue(data.scope) && this.hideScopeInUrl) { + return; + } + queryParams[this.searchConfig.getCurrentSearchInstanceParam(key)] = data[key]; + }); void this.router.navigate(this.getSearchLinkParts(), { queryParams: queryParams, diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts index 69f3a5fb7dc..7a2ed8b8f29 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts @@ -74,7 +74,7 @@ export class SearchFacetOptionComponent implements OnInit { */ searchLink: string; - paginationId: string; + searchInstanceId: string; constructor(protected searchService: SearchService, protected filterService: SearchFilterService, @@ -90,7 +90,7 @@ export class SearchFacetOptionComponent implements OnInit { * Initializes all observable instance variables and starts listening to them */ ngOnInit(): void { - this.paginationId = this.searchConfigService.paginationID; + this.searchInstanceId = this.searchConfigService.searchInstanceId; this.searchLink = this.getSearchLink(); this.isVisible = this.isChecked().pipe(map((checked: boolean) => !checked)); this.addQueryParams$ = this.updateAddParams(); @@ -100,7 +100,7 @@ export class SearchFacetOptionComponent implements OnInit { * Checks if a value for this filter is currently active */ isChecked(): Observable { - return this.filterService.isFilterActiveWithValue(this.filterConfig.paramName, this.getFacetValue()); + return this.filterService.isFilterActiveWithValue(this.filterConfig.paramName, this.getFacetValue(), this.searchInstanceId); } /** diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts index 4f46a5dd2a7..df0144b94f9 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts @@ -82,7 +82,8 @@ describe('SearchFacetRangeOptionComponent', () => { { provide: SearchConfigurationService, useValue: { searchOptions: of({}), - paginationId: 'page-id', + searchInstanceId: 'page-id', + getCurrentSearchInstanceFilterParam: (param: string) => `page-id.${param}`, }, }, { @@ -136,8 +137,10 @@ describe('SearchFacetRangeOptionComponent', () => { }; (comp as any).updateChangeParams(); expect(comp.changeQueryParams).toEqual({ - [mockFilterConfig.paramName + RANGE_FILTER_MIN_SUFFIX]: [50], - [mockFilterConfig.paramName + RANGE_FILTER_MAX_SUFFIX]: [60], + [`page-id.${mockFilterConfig.paramName}${RANGE_FILTER_MIN_SUFFIX}`]: [50], + [`page-id.${mockFilterConfig.paramName}${RANGE_FILTER_MAX_SUFFIX}`]: [60], + [mockFilterConfig.paramName + RANGE_FILTER_MIN_SUFFIX]: null, + [mockFilterConfig.paramName + RANGE_FILTER_MAX_SUFFIX]: null, ['page-id.page']: 1, }); }); diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.ts index 8e72b766bf8..d0381e92b73 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.ts @@ -107,7 +107,7 @@ export class SearchFacetRangeOptionComponent implements OnInit, OnDestroy { * Checks if a value for this filter is currently active */ private isChecked(): Observable { - return this.filterService.isFilterActiveWithValue(this.filterConfig.paramName, this.filterValue.value); + return this.filterService.isFilterActiveWithValue(this.filterConfig.paramName, this.filterValue.value, this.searchConfigService.searchInstanceId); } /** @@ -127,10 +127,13 @@ export class SearchFacetRangeOptionComponent implements OnInit, OnDestroy { const parts = this.filterValue.value.split(rangeDelimiter); const min = parts.length > 1 ? Number(parts[0].trim()) : this.filterValue.value; const max = parts.length > 1 ? Number(parts[1].trim()) : this.filterValue.value; - const page = this.paginationService.getPageParam(this.searchConfigService.paginationID); + const page = this.paginationService.getPageParam(this.searchConfigService.searchInstanceId); + const filterParamName = this.searchConfigService.getCurrentSearchInstanceFilterParam(this.filterConfig.paramName); this.changeQueryParams = { - [this.filterConfig.paramName + RANGE_FILTER_MIN_SUFFIX]: [min], - [this.filterConfig.paramName + RANGE_FILTER_MAX_SUFFIX]: max === new Date().getUTCFullYear() ? null : [max], + [filterParamName + RANGE_FILTER_MIN_SUFFIX]: [min], + [filterParamName + RANGE_FILTER_MAX_SUFFIX]: max === new Date().getUTCFullYear() ? null : [max], + [this.filterConfig.paramName + RANGE_FILTER_MIN_SUFFIX]: null, + [this.filterConfig.paramName + RANGE_FILTER_MAX_SUFFIX]: null, [page]: 1, }; } diff --git a/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.spec.ts b/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.spec.ts index 1f55941f00b..ba46e87f5e6 100644 --- a/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.spec.ts +++ b/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.spec.ts @@ -148,8 +148,11 @@ describe('SearchRangeFilterComponent', () => { it('should call navigate on the router with the right searchlink and parameters', () => { expect(router.navigate).toHaveBeenCalledWith(searchUrl.split('/'), { queryParams: { - [mockFilterConfig.paramName + minSuffix]: [1900], - [mockFilterConfig.paramName + maxSuffix]: [1950], + [`test-id.${mockFilterConfig.paramName}${minSuffix}`]: [1900], + [`test-id.${mockFilterConfig.paramName}${maxSuffix}`]: [1950], + [mockFilterConfig.paramName + minSuffix]: null, + [mockFilterConfig.paramName + maxSuffix]: null, + 'test-id.page': 1, }, queryParamsHandling: 'merge', }); diff --git a/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.ts b/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.ts index a546d1ba707..7107517d91c 100644 --- a/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.ts +++ b/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.ts @@ -135,8 +135,15 @@ export class SearchRangeFilterComponent extends SearchFacetFilterComponent imple this.max = yearFromString(this.filterConfig.maxValue) || this.max; this.minLabel = this.translateService.instant('search.filters.filter.' + this.filterConfig.name + '.min.placeholder'); this.maxLabel = this.translateService.instant('search.filters.filter.' + this.filterConfig.name + '.max.placeholder'); - const iniMin = this.route.getQueryParameterValue(this.filterConfig.paramName + RANGE_FILTER_MIN_SUFFIX).pipe(startWith(undefined)); - const iniMax = this.route.getQueryParameterValue(this.filterConfig.paramName + RANGE_FILTER_MAX_SUFFIX).pipe(startWith(undefined)); + const filterParamName = this.searchConfigService.getCurrentSearchInstanceFilterParam(this.filterConfig.paramName); + const iniMin = observableCombineLatest([ + this.route.getQueryParameterValue(filterParamName + RANGE_FILTER_MIN_SUFFIX).pipe(startWith(undefined)), + this.route.getQueryParameterValue(this.filterConfig.paramName + RANGE_FILTER_MIN_SUFFIX).pipe(startWith(undefined)), + ]).pipe(map(([instanceMin, legacyMin]: [string, string]) => hasValue(instanceMin) ? instanceMin : legacyMin)); + const iniMax = observableCombineLatest([ + this.route.getQueryParameterValue(filterParamName + RANGE_FILTER_MAX_SUFFIX).pipe(startWith(undefined)), + this.route.getQueryParameterValue(this.filterConfig.paramName + RANGE_FILTER_MAX_SUFFIX).pipe(startWith(undefined)), + ]).pipe(map(([instanceMax, legacyMax]: [string, string]) => hasValue(instanceMax) ? instanceMax : legacyMax)); this.subs.push(observableCombineLatest([iniMin, iniMax]).pipe( map(([min, max]: [string, string]) => { const minimum = hasValue(min) ? Number(min) : this.min; @@ -177,8 +184,11 @@ export class SearchRangeFilterComponent extends SearchFacetFilterComponent imple void this.router.navigate(this.getSearchLinkParts(), { queryParams: { - [this.filterConfig.paramName + RANGE_FILTER_MIN_SUFFIX]: newMin, - [this.filterConfig.paramName + RANGE_FILTER_MAX_SUFFIX]: newMax, + [this.searchConfigService.getCurrentSearchInstanceFilterParam(this.filterConfig.paramName) + RANGE_FILTER_MIN_SUFFIX]: newMin, + [this.searchConfigService.getCurrentSearchInstanceFilterParam(this.filterConfig.paramName) + RANGE_FILTER_MAX_SUFFIX]: newMax, + [this.filterConfig.paramName + RANGE_FILTER_MIN_SUFFIX]: null, + [this.filterConfig.paramName + RANGE_FILTER_MAX_SUFFIX]: null, + [this.searchConfigService.getCurrentPageParam()]: 1, }, queryParamsHandling: 'merge', }); diff --git a/src/app/shared/search/search-results/search-results.component.html b/src/app/shared/search/search-results/search-results.component.html index e1039b8d31b..865b77759f8 100644 --- a/src/app/shared/search/search-results/search-results.component.html +++ b/src/app/shared/search/search-results/search-results.component.html @@ -30,11 +30,13 @@

{{ (configuration ? configuration + '.search.results.head' : 'search.results [selectionConfig]="selectionConfig" [linkType]="linkType" [context]="context" + [viewMode]="searchConfig?.view" [hidePaginationDetail]="hidePaginationDetail" [showThumbnails]="showThumbnails" (contentChange)="contentChange.emit($event)" (deselectObject)="deselectObject.emit($event)" (selectObject)="selectObject.emit($event)"> + } @@ -54,7 +56,7 @@

{{ (configuration ? configuration + '.search.results.head' : 'search.results
{{ 'search.results.no-results' | translate }} {{"search.results.no-results-link" | translate}} diff --git a/src/app/shared/search/search-results/search-results.component.ts b/src/app/shared/search/search-results/search-results.component.ts index 421f361bc00..58294432199 100644 --- a/src/app/shared/search/search-results/search-results.component.ts +++ b/src/app/shared/search/search-results/search-results.component.ts @@ -5,7 +5,10 @@ import { Input, Output, } from '@angular/core'; -import { RouterLink } from '@angular/router'; +import { + Params, + RouterLink, +} from '@angular/router'; import { TranslateModule } from '@ngx-translate/core'; import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader'; import { @@ -188,4 +191,15 @@ export class SearchResultsComponent { return result; } + + getExactMatchQueryParams(): Params { + if (hasNoValue(this.searchConfig?.pagination?.id)) { + return { + query: this.surroundStringWithQuotes(this.searchConfig?.query), + }; + } + return { + [`${this.searchConfig?.pagination?.id}.query`]: this.surroundStringWithQuotes(this.searchConfig?.query), + }; + } } diff --git a/src/app/shared/search/search-settings/search-settings.component.ts b/src/app/shared/search/search-settings/search-settings.component.ts index 058986c820a..24b3bc32f8a 100644 --- a/src/app/shared/search/search-settings/search-settings.component.ts +++ b/src/app/shared/search/search-settings/search-settings.component.ts @@ -56,7 +56,7 @@ export class SearchSettingsComponent { */ reloadOrder(event: Event) { const values = (event.target as HTMLInputElement).value.split(','); - this.paginationService.updateRoute(this.searchConfigurationService.paginationID, { + this.paginationService.updateRoute(this.searchConfigurationService.searchInstanceId, { sortField: values[0], sortDirection: values[1] as SortDirection, page: 1, diff --git a/src/app/shared/search/search-switch-configuration/search-switch-configuration.component.spec.ts b/src/app/shared/search/search-switch-configuration/search-switch-configuration.component.spec.ts index 28fd6c793dd..ebdf413ef74 100644 --- a/src/app/shared/search/search-switch-configuration/search-switch-configuration.component.spec.ts +++ b/src/app/shared/search/search-switch-configuration/search-switch-configuration.component.spec.ts @@ -111,7 +111,7 @@ describe('SearchSwitchConfigurationComponent', () => { spyOn((comp as any).changeConfiguration, 'emit'); comp.selectedOption = configurationList[1]; const navigationExtras: NavigationExtras = { - queryParams: { configuration: MyDSpaceConfigurationValueType.Workflow }, + queryParams: { 'test-id.configuration': MyDSpaceConfigurationValueType.Workflow }, }; fixture.detectChanges(); diff --git a/src/app/shared/search/search-switch-configuration/search-switch-configuration.component.ts b/src/app/shared/search/search-switch-configuration/search-switch-configuration.component.ts index 0e244fdf224..e4ef815acc4 100644 --- a/src/app/shared/search/search-switch-configuration/search-switch-configuration.component.ts +++ b/src/app/shared/search/search-switch-configuration/search-switch-configuration.component.ts @@ -88,7 +88,9 @@ export class SearchSwitchConfigurationComponent implements OnDestroy, OnInit { */ onSelect() { const navigationExtras: NavigationExtras = { - queryParams: { configuration: this.selectedOption.value }, + queryParams: { + [this.searchConfigService.getCurrentSearchInstanceParam('configuration')]: this.selectedOption.value, + }, }; this.changeConfiguration.emit(this.selectedOption); diff --git a/src/app/shared/search/search.component.spec.ts b/src/app/shared/search/search.component.spec.ts index 0a8d63f1ab7..62e0daf9ce9 100644 --- a/src/app/shared/search/search.component.spec.ts +++ b/src/app/shared/search/search.component.spec.ts @@ -200,10 +200,11 @@ export function configureSearchComponentTestingModule(compType, additionalDeclar getCurrentScope: of('test-id'), getCurrentSort: of(sortOptionsList[0]), updateFixedFilter: jasmine.createSpy('updateFixedFilter'), - setPaginationId: jasmine.createSpy('setPaginationId'), + setSearchInstanceId: jasmine.createSpy('setSearchInstanceId'), }); + searchConfigurationServiceStub.getCurrentSearchInstanceParam = (param: string) => `${paginationId}.${param}`; - searchConfigurationServiceStub.setPaginationId.and.callFake((pageId) => { + searchConfigurationServiceStub.setSearchInstanceId.and.callFake((pageId) => { paginatedSearchOptions$.next(Object.assign(paginatedSearchOptions$.value, { pagination: Object.assign(new PaginationComponentOptions(), { id: pageId, @@ -251,13 +252,6 @@ export function configureSearchComponentTestingModule(compType, additionalDeclar ], schemas: [NO_ERRORS_SCHEMA], }).overrideComponent(compType, { - add: { - changeDetection: ChangeDetectionStrategy.Default, - providers: [{ - provide: SearchConfigurationService, - useValue: searchConfigurationServiceStub, - }], - }, remove: { imports: [ PageWithSidebarComponent, @@ -268,7 +262,14 @@ export function configureSearchComponentTestingModule(compType, additionalDeclar SearchLabelsComponent, ], }, - + }).overrideComponent(compType, { + set: { + changeDetection: ChangeDetectionStrategy.Default, + providers: [{ + provide: SearchConfigurationService, + useValue: searchConfigurationServiceStub, + }], + }, }).compileComponents(); } @@ -281,7 +282,7 @@ describe('SearchComponent', () => { fixture = TestBed.createComponent(SearchComponent); comp = fixture.componentInstance; // SearchComponent test instance comp.inPlaceSearch = false; - comp.paginationId = paginationId; + comp.searchInstanceId = paginationId; comp.hiddenQuery = hiddenQuery; spyOn((comp as any), 'getSearchOptions').and.returnValue(paginatedSearchOptions$.asObservable()); diff --git a/src/app/shared/search/search.component.ts b/src/app/shared/search/search.component.ts index 6969a741e48..1048fe70114 100644 --- a/src/app/shared/search/search.component.ts +++ b/src/app/shared/search/search.component.ts @@ -153,9 +153,9 @@ export class SearchComponent implements OnDestroy, OnInit { @Input() linkType: CollectionElementLinkType; /** - * The pagination id used in the search + * The search instance id used in the search */ - @Input() paginationId = 'spc'; + @Input() searchInstanceId = 'spc'; /** * Whether or not the search bar should be visible @@ -374,17 +374,17 @@ export class SearchComponent implements OnDestroy, OnInit { } if (this.useUniquePageId) { - // Create an unique pagination id related to the instance of the SearchComponent - this.paginationId = uniqueId(this.paginationId); + // Create a unique search instance id related to this SearchComponent. + this.searchInstanceId = uniqueId(this.searchInstanceId); } - this.searchConfigService.setPaginationId(this.paginationId); + this.searchConfigService.setSearchInstanceId(this.searchInstanceId); if (hasValue(this.configuration)) { - this.routeService.setParameter('configuration', this.configuration); + this.routeService.setParameter(this.searchConfigService.getCurrentSearchInstanceParam('configuration'), this.configuration); } if (hasValue(this.fixedFilterQuery)) { - this.routeService.setParameter('fixedFilterQuery', this.fixedFilterQuery); + this.routeService.setParameter(this.searchConfigService.getCurrentSearchInstanceParam('fixedFilterQuery'), this.fixedFilterQuery); } this.currentScope$ = this.routeService.getQueryParameterValue('scope').pipe( @@ -406,7 +406,7 @@ export class SearchComponent implements OnDestroy, OnInit { const sortOption$: Observable = searchSortOptions$.pipe( switchMap((searchSortOptions: SortOptions[]) => { const defaultSort: SortOptions = searchSortOptions[0]; - return this.searchConfigService.getCurrentSort(this.paginationId, defaultSort); + return this.searchConfigService.getCurrentSort(this.searchInstanceId, defaultSort); }), distinctUntilChanged(), ); @@ -414,8 +414,8 @@ export class SearchComponent implements OnDestroy, OnInit { this.subs.push(combineLatest([configuration$, searchSortOptions$, searchOptions$, sortOption$, this.currentScope$]).pipe( filter(([configuration, searchSortOptions, searchOptions, sortOption, scope]: [string, SortOptions[], PaginatedSearchOptions, SortOptions, string]) => { - // filter for search options related to instanced paginated id - return searchOptions.pagination.id === this.paginationId; + // filter for search options related to this search instance id + return searchOptions.pagination.id === this.searchInstanceId; }), debounceTime(100), ).subscribe(([configuration, searchSortOptions, searchOptions, sortOption, scope]: [string, SortOptions[], PaginatedSearchOptions, SortOptions, string]) => { diff --git a/src/app/shared/search/themed-search.component.ts b/src/app/shared/search/themed-search.component.ts index e76a4d2f1a5..8cfc4e6f104 100644 --- a/src/app/shared/search/themed-search.component.ts +++ b/src/app/shared/search/themed-search.component.ts @@ -38,7 +38,7 @@ export class ThemedSearchComponent extends ThemedComponent { 'useCachedVersionIfAvailable', 'inPlaceSearch', 'linkType', - 'paginationId', + 'searchInstanceId', 'searchEnabled', 'sideBarWidth', 'searchFormPlaceholder', @@ -76,7 +76,7 @@ export class ThemedSearchComponent extends ThemedComponent { @Input() linkType: CollectionElementLinkType; - @Input() paginationId: string; + @Input() searchInstanceId: string; @Input() searchEnabled: boolean; diff --git a/src/app/shared/testing/pagination-service.stub.ts b/src/app/shared/testing/pagination-service.stub.ts index 16a2f48ce75..7119fea3e0f 100644 --- a/src/app/shared/testing/pagination-service.stub.ts +++ b/src/app/shared/testing/pagination-service.stub.ts @@ -24,6 +24,6 @@ export class PaginationServiceStub { updateRouteWithUrl = jasmine.createSpy('updateRouteWithUrl'); clearPagination = jasmine.createSpy('clearPagination'); getRouteParameterValue = jasmine.createSpy('getRouteParameterValue').and.returnValue(of('')); - getPageParam = jasmine.createSpy('getPageParam').and.returnValue(`${this.pagination.id}.page`); + getPageParam = jasmine.createSpy('getPageParam').and.callFake((paginationId: string) => `${paginationId}.page`); } diff --git a/src/app/shared/testing/search-configuration-service.stub.ts b/src/app/shared/testing/search-configuration-service.stub.ts index e06f2ab6910..0c481f230e2 100644 --- a/src/app/shared/testing/search-configuration-service.stub.ts +++ b/src/app/shared/testing/search-configuration-service.stub.ts @@ -17,7 +17,7 @@ import { SearchOptions } from '../search/models/search-options.model'; */ export class SearchConfigurationServiceStub { - public paginationID = 'test-id'; + public searchInstanceId = 'test-id'; public searchOptions: BehaviorSubject = new BehaviorSubject(new SearchOptions({})); public paginatedSearchOptions: BehaviorSubject = new BehaviorSubject(new PaginatedSearchOptions({})); @@ -30,6 +30,18 @@ export class SearchConfigurationServiceStub { return of([]); } + getCurrentSearchInstanceParam(param: string) { + return `${this.searchInstanceId}.${param}`; + } + + getCurrentSearchInstanceFilterParam(param: string) { + return `${this.searchInstanceId}.${param}`; + } + + getCurrentPageParam() { + return `${this.searchInstanceId}.page`; + } + getCurrentScope(a) { return of('test-id'); } From 280bfec20f21605914cb02113a1ddc32e52ba690 Mon Sep 17 00:00:00 2001 From: Ali Jaber Date: Mon, 8 Jun 2026 01:15:02 -0400 Subject: [PATCH 2/9] 141627: Migrate legacy unprefixed search params to searchInstanceId-prefixed params on load --- .../search-configuration.service.spec.ts | 23 +++++++ .../search/search-configuration.service.ts | 19 ++++++ .../shared/search/search.component.spec.ts | 66 ++++++++++++++++++- src/app/shared/search/search.component.ts | 46 +++++++++++++ 4 files changed, 153 insertions(+), 1 deletion(-) diff --git a/src/app/core/shared/search/search-configuration.service.spec.ts b/src/app/core/shared/search/search-configuration.service.spec.ts index e96c67937ef..672dab026d0 100644 --- a/src/app/core/shared/search/search-configuration.service.spec.ts +++ b/src/app/core/shared/search/search-configuration.service.spec.ts @@ -300,6 +300,29 @@ describe('SearchConfigurationService', () => { }); }); + describe('isLegacySearchParam', () => { + it('should return true for unprefixed scoped search params', () => { + ['configuration', 'scope', 'query', 'dsoType', 'view'].forEach((param: string) => { + expect(service.isLegacySearchParam(param)).toBeTrue(); + }); + }); + + it('should return true for unprefixed filter params', () => { + expect(service.isLegacySearchParam('f.author')).toBeTrue(); + expect(service.isLegacySearchParam('f.dateIssued.max')).toBeTrue(); + }); + + it('should return false for params that are already prefixed with a search instance id', () => { + expect(service.isLegacySearchParam(`${defaults.pagination.id}.query`)).toBeFalse(); + expect(service.isLegacySearchParam(`${defaults.pagination.id}.f.author`)).toBeFalse(); + }); + + it('should return false for unrelated params', () => { + expect(service.isLegacySearchParam('page')).toBeFalse(); + expect(service.isLegacySearchParam('spc.page')).toBeFalse(); + }); + }); + describe('unselectAppliedFilterParams', () => { let appliedFilter: AppliedFilter; diff --git a/src/app/core/shared/search/search-configuration.service.ts b/src/app/core/shared/search/search-configuration.service.ts index 6e6851a2c8a..5b0fae19e31 100644 --- a/src/app/core/shared/search/search-configuration.service.ts +++ b/src/app/core/shared/search/search-configuration.service.ts @@ -89,6 +89,13 @@ export class SearchConfigurationService implements OnDestroy { */ public searchInstanceId = 'spc'; + /** + * The names of the query parameters that are scoped to a search instance, but that still accept a + * legacy (unprefixed) value for backwards compatibility. Filter parameters (prefixed with `f.`) are + * handled separately, see {@link isLegacySearchParam}. + */ + protected readonly legacyScopedQueryParams: string[] = ['configuration', 'scope', 'query', 'dsoType', 'view']; + /** * Emits the current search options */ @@ -348,6 +355,18 @@ export class SearchConfigurationService implements OnDestroy { return this.getSearchInstanceParam(searchInstanceId, 'f.'); } + /** + * Whether the given query parameter is a legacy (unprefixed) search parameter that has a + * search-instance-prefixed equivalent (e.g. `query`, `scope` or a `f.xxx` filter). These + * parameters are still read for backwards compatibility, but should be migrated to their + * prefixed form so they don't get mixed with newly added prefixed parameters. + * + * @param paramName The query parameter name + */ + isLegacySearchParam(paramName: string): boolean { + return this.legacyScopedQueryParams.includes(paramName) || paramName.startsWith('f.'); + } + getCurrentPageParam(): string { return this.paginationService.getPageParam(this.searchInstanceId); } diff --git a/src/app/shared/search/search.component.spec.ts b/src/app/shared/search/search.component.spec.ts index 62e0daf9ce9..03546364ed3 100644 --- a/src/app/shared/search/search.component.spec.ts +++ b/src/app/shared/search/search.component.spec.ts @@ -12,7 +12,10 @@ import { } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; -import { ActivatedRoute } from '@angular/router'; +import { + ActivatedRoute, + convertToParamMap, +} from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbCollapseModule } from '@ng-bootstrap/ng-bootstrap'; import { Store } from '@ngrx/store'; @@ -184,6 +187,9 @@ const routeServiceStub = { getQueryParamsWithPrefix: () => { return of(null); }, + getQueryParamMap: () => { + return of(convertToParamMap({})); + }, setParameter: (key: any, value: any) => { return; }, @@ -203,6 +209,7 @@ export function configureSearchComponentTestingModule(compType, additionalDeclar setSearchInstanceId: jasmine.createSpy('setSearchInstanceId'), }); searchConfigurationServiceStub.getCurrentSearchInstanceParam = (param: string) => `${paginationId}.${param}`; + searchConfigurationServiceStub.isLegacySearchParam = (param: string) => ['configuration', 'scope', 'query', 'dsoType', 'view'].includes(param) || param.startsWith('f.'); searchConfigurationServiceStub.setSearchInstanceId.and.callFake((pageId) => { paginatedSearchOptions$.next(Object.assign(paginatedSearchOptions$.value, { @@ -343,6 +350,63 @@ describe('SearchComponent', () => { expect(comp.resultFound.emit).toHaveBeenCalledWith(expectedResults); })); + describe('migrateLegacySearchParams', () => { + let navigateSpy: jasmine.Spy; + + beforeEach(() => { + comp.platformId = 'browser'; + comp.searchInstanceId = paginationId; + navigateSpy = spyOn((comp as any).router, 'navigate'); + }); + + it('should replace legacy (unprefixed) search params with their prefixed equivalent', () => { + spyOn((comp as any).routeService, 'getQueryParamMap').and.returnValue(of(convertToParamMap({ + query: 'cats', + 'f.author': 'Smith', + }))); + + (comp as any).migrateLegacySearchParams(); + + expect(navigateSpy).toHaveBeenCalledWith([], { + queryParams: { + query: null, + [`${paginationId}.query`]: 'cats', + 'f.author': null, + [`${paginationId}.f.author`]: 'Smith', + }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + }); + + it('should not navigate when there are no legacy search params', () => { + spyOn((comp as any).routeService, 'getQueryParamMap').and.returnValue(of(convertToParamMap({ + [`${paginationId}.query`]: 'cats', + }))); + + (comp as any).migrateLegacySearchParams(); + + expect(navigateSpy).not.toHaveBeenCalled(); + }); + + it('should drop the legacy param without overriding an existing prefixed param', () => { + spyOn((comp as any).routeService, 'getQueryParamMap').and.returnValue(of(convertToParamMap({ + query: 'legacy', + [`${paginationId}.query`]: 'prefixed', + }))); + + (comp as any).migrateLegacySearchParams(); + + expect(navigateSpy).toHaveBeenCalledWith([], { + queryParams: { + query: null, + }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + }); + }); + describe('when the open sidebar button is clicked in mobile view', () => { beforeEach(() => { diff --git a/src/app/shared/search/search.component.ts b/src/app/shared/search/search.component.ts index 1048fe70114..cfd589de054 100644 --- a/src/app/shared/search/search.component.ts +++ b/src/app/shared/search/search.component.ts @@ -1,5 +1,6 @@ import { AsyncPipe, + isPlatformBrowser, isPlatformServer, NgTemplateOutlet, } from '@angular/common'; @@ -16,6 +17,7 @@ import { } from '@angular/core'; import { NavigationStart, + Params, Router, } from '@angular/router'; import { TranslateModule } from '@ngx-translate/core'; @@ -32,6 +34,7 @@ import { filter, map, switchMap, + take, } from 'rxjs/operators'; import { @@ -380,6 +383,10 @@ export class SearchComponent implements OnDestroy, OnInit { this.searchConfigService.setSearchInstanceId(this.searchInstanceId); + if (isPlatformBrowser(this.platformId)) { + this.migrateLegacySearchParams(); + } + if (hasValue(this.configuration)) { this.routeService.setParameter(this.searchConfigService.getCurrentSearchInstanceParam('configuration'), this.configuration); } @@ -586,6 +593,45 @@ export class SearchComponent implements OnDestroy, OnInit { } } + /** + * Detect legacy (unprefixed) search parameters in the current URL and replace them with their + * search-instance-prefixed equivalents (e.g. `query` becomes `spc.query`, `f.author` becomes + * `spc.f.author`). This keeps backwards compatibility with old search URLs while making sure that + * subsequent search interactions (entering a new query, adding a filter, ...) operate on the + * prefixed parameters only, instead of mixing or dropping the legacy ones. + * @private + */ + private migrateLegacySearchParams(): void { + this.subs.push(this.routeService.getQueryParamMap().pipe(take(1)).subscribe((queryParamMap) => { + const prefix = `${this.searchInstanceId}.`; + const updatedParams: Params = {}; + let hasLegacyParams = false; + + queryParamMap.keys + .filter((key: string) => this.searchConfigService.isLegacySearchParam(key)) + .forEach((key: string) => { + hasLegacyParams = true; + // Remove the legacy parameter from the URL + updatedParams[key] = null; + // Only move its value(s) to the prefixed parameter when no prefixed value is set yet, + // so an existing prefixed parameter always takes precedence over the legacy one. + const prefixedKey = `${prefix}${key}`; + if (!queryParamMap.has(prefixedKey)) { + const values: string[] = queryParamMap.getAll(key); + updatedParams[prefixedKey] = values.length > 1 ? values : values[0]; + } + }); + + if (hasLegacyParams) { + void this.router.navigate([], { + queryParams: updatedParams, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + } + })); + } + /** * Get the UUID from a DSO url * Return null if the url isn't an object page (allowedObjectPaths) or the UUID couldn't be found From 132a71578b248ee9b5067e3cea4b17088710b451 Mon Sep 17 00:00:00 2001 From: Ali Jaber Date: Thu, 16 Jul 2026 09:06:34 -0400 Subject: [PATCH 3/9] 141627: inject SEARCH_CONFIG_SERVICE token in search facet/label components to use scoped config service --- .../search-facet-option/search-facet-option.component.spec.ts | 4 ++-- .../search-facet-option/search-facet-option.component.ts | 4 +++- .../search-facet-range-option.component.spec.ts | 4 ++-- .../search-facet-range-option.component.ts | 4 +++- .../search-facet-selected-option.component.spec.ts | 4 ++-- .../search-facet-selected-option.component.ts | 4 +++- .../search-labels/search-label/search-label.component.spec.ts | 4 ++-- .../search-labels/search-label/search-label.component.ts | 4 +++- 8 files changed, 20 insertions(+), 12 deletions(-) diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.spec.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.spec.ts index d761a8d95db..d7e92f35e98 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.spec.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.spec.ts @@ -19,8 +19,8 @@ import { of } from 'rxjs'; import { PaginationService } from '../../../../../../core/pagination/pagination.service'; import { SearchService } from '../../../../../../core/shared/search/search.service'; -import { SearchConfigurationService } from '../../../../../../core/shared/search/search-configuration.service'; import { SearchFilterService } from '../../../../../../core/shared/search/search-filter.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../../../../my-dspace-page/my-dspace-configuration.service'; import { ActivatedRouteStub } from '../../../../../../shared/testing/active-router.stub'; import { LiveRegionService } from '../../../../../live-region/live-region.service'; import { getLiveRegionServiceStub } from '../../../../../live-region/live-region.service.stub'; @@ -83,7 +83,7 @@ describe('SearchFacetOptionComponent', () => { { provide: SearchService, useValue: searchService }, { provide: Router, useValue: router }, { provide: PaginationService, useValue: paginationService }, - { provide: SearchConfigurationService, useValue: searchConfigurationService }, + { provide: SEARCH_CONFIG_SERVICE, useValue: searchConfigurationService }, { provide: SearchFilterService, useValue: searchFilterService }, { provide: ActivatedRoute, useValue: new ActivatedRouteStub() }, { provide: LiveRegionService, useValue: getLiveRegionServiceStub() }, diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts index 7a2ed8b8f29..eedc2b8057c 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts @@ -1,6 +1,7 @@ import { AsyncPipe } from '@angular/common'; import { Component, + Inject, Input, OnInit, } from '@angular/core'; @@ -20,6 +21,7 @@ import { PaginationService } from '../../../../../../core/pagination/pagination. import { SearchService } from '../../../../../../core/shared/search/search.service'; import { SearchConfigurationService } from '../../../../../../core/shared/search/search-configuration.service'; import { SearchFilterService } from '../../../../../../core/shared/search/search-filter.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../../../../my-dspace-page/my-dspace-configuration.service'; import { LiveRegionService } from '../../../../../../shared/live-region/live-region.service'; import { currentPath } from '../../../../../utils/route.utils'; import { ShortNumberPipe } from '../../../../../utils/short-number.pipe'; @@ -78,7 +80,7 @@ export class SearchFacetOptionComponent implements OnInit { constructor(protected searchService: SearchService, protected filterService: SearchFilterService, - protected searchConfigService: SearchConfigurationService, + @Inject(SEARCH_CONFIG_SERVICE) protected searchConfigService: SearchConfigurationService, protected router: Router, protected paginationService: PaginationService, protected liveRegionService: LiveRegionService, diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts index df0144b94f9..9571b785b5b 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts @@ -19,8 +19,8 @@ import { of } from 'rxjs'; import { PaginationService } from '../../../../../../core/pagination/pagination.service'; import { SearchService } from '../../../../../../core/shared/search/search.service'; -import { SearchConfigurationService } from '../../../../../../core/shared/search/search-configuration.service'; import { SearchFilterService } from '../../../../../../core/shared/search/search-filter.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../../../../my-dspace-page/my-dspace-configuration.service'; import { PaginationComponentOptions } from '../../../../../pagination/pagination-component-options.model'; import { PaginationServiceStub } from '../../../../../testing/pagination-service.stub'; import { RouterStub } from '../../../../../testing/router.stub'; @@ -80,7 +80,7 @@ describe('SearchFacetRangeOptionComponent', () => { { provide: Router, useValue: new RouterStub() }, { provide: PaginationService, useValue: paginationService }, { - provide: SearchConfigurationService, useValue: { + provide: SEARCH_CONFIG_SERVICE, useValue: { searchOptions: of({}), searchInstanceId: 'page-id', getCurrentSearchInstanceFilterParam: (param: string) => `page-id.${param}`, diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.ts index d0381e92b73..f34bf0cb709 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.ts @@ -1,6 +1,7 @@ import { AsyncPipe } from '@angular/common'; import { Component, + Inject, Input, OnDestroy, OnInit, @@ -20,6 +21,7 @@ import { PaginationService } from '../../../../../../core/pagination/pagination. import { SearchService } from '../../../../../../core/shared/search/search.service'; import { SearchConfigurationService } from '../../../../../../core/shared/search/search-configuration.service'; import { SearchFilterService } from '../../../../../../core/shared/search/search-filter.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../../../../my-dspace-page/my-dspace-configuration.service'; import { hasValue } from '../../../../../empty.util'; import { currentPath } from '../../../../../utils/route.utils'; import { ShortNumberPipe } from '../../../../../utils/short-number.pipe'; @@ -86,7 +88,7 @@ export class SearchFacetRangeOptionComponent implements OnInit, OnDestroy { constructor(protected searchService: SearchService, protected filterService: SearchFilterService, - protected searchConfigService: SearchConfigurationService, + @Inject(SEARCH_CONFIG_SERVICE) protected searchConfigService: SearchConfigurationService, protected router: Router, protected paginationService: PaginationService, ) { diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.spec.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.spec.ts index 1faeb045833..e3365620786 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.spec.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.spec.ts @@ -13,8 +13,8 @@ import { TranslateModule } from '@ngx-translate/core'; import { PaginationService } from '../../../../../../core/pagination/pagination.service'; import { SearchService } from '../../../../../../core/shared/search/search.service'; -import { SearchConfigurationService } from '../../../../../../core/shared/search/search-configuration.service'; import { SearchFilterService } from '../../../../../../core/shared/search/search-filter.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../../../../my-dspace-page/my-dspace-configuration.service'; import { PaginationComponentOptions } from '../../../../../pagination/pagination-component-options.model'; import { ActivatedRouteStub } from '../../../../../testing/active-router.stub'; import { PaginationServiceStub } from '../../../../../testing/pagination-service.stub'; @@ -72,7 +72,7 @@ describe('SearchFacetSelectedOptionComponent', () => { { provide: SearchService, useValue:searchService }, { provide: Router, useValue: router }, { provide: PaginationService, useValue: paginationService }, - { provide: SearchConfigurationService, useValue: searchConfigurationService }, + { provide: SEARCH_CONFIG_SERVICE, useValue: searchConfigurationService }, { provide: SearchFilterService, useValue: searchFilterService }, { provide: ActivatedRoute, useValue: new ActivatedRouteStub() }, ], diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.ts index 2732a116e7f..9936a343f92 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.ts @@ -1,6 +1,7 @@ import { AsyncPipe } from '@angular/common'; import { Component, + Inject, Input, OnInit, } from '@angular/core'; @@ -16,6 +17,7 @@ import { PaginationService } from '../../../../../../core/pagination/pagination. import { SearchService } from '../../../../../../core/shared/search/search.service'; import { SearchConfigurationService } from '../../../../../../core/shared/search/search-configuration.service'; import { SearchFilterService } from '../../../../../../core/shared/search/search-filter.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../../../../my-dspace-page/my-dspace-configuration.service'; import { currentPath } from '../../../../../utils/route.utils'; import { AppliedFilter } from '../../../../models/applied-filter.model'; import { SearchFilterConfig } from '../../../../models/search-filter-config.model'; @@ -66,7 +68,7 @@ export class SearchFacetSelectedOptionComponent implements OnInit { protected router: Router, protected searchFilterService: SearchFilterService, protected searchService: SearchService, - protected searchConfigService: SearchConfigurationService, + @Inject(SEARCH_CONFIG_SERVICE) protected searchConfigService: SearchConfigurationService, ) { } diff --git a/src/app/shared/search/search-labels/search-label/search-label.component.spec.ts b/src/app/shared/search/search-labels/search-label/search-label.component.spec.ts index 179f1714ebc..514fd084e45 100644 --- a/src/app/shared/search/search-labels/search-label/search-label.component.spec.ts +++ b/src/app/shared/search/search-labels/search-label/search-label.component.spec.ts @@ -17,8 +17,8 @@ import { TranslateModule } from '@ngx-translate/core'; import { PaginationService } from '../../../../core/pagination/pagination.service'; import { SearchService } from '../../../../core/shared/search/search.service'; -import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service'; import { SearchFilterService } from '../../../../core/shared/search/search-filter.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../../my-dspace-page/my-dspace-configuration.service'; import { PaginationComponentOptions } from '../../../pagination/pagination-component-options.model'; import { ActivatedRouteStub } from '../../../testing/active-router.stub'; import { PaginationServiceStub } from '../../../testing/pagination-service.stub'; @@ -81,7 +81,7 @@ describe('SearchLabelComponent', () => { ], providers: [ { provide: PaginationService, useValue: paginationService }, - { provide: SearchConfigurationService, useValue: searchConfigurationService }, + { provide: SEARCH_CONFIG_SERVICE, useValue: searchConfigurationService }, { provide: SearchFilterService, useValue: searchFilterService }, { provide: SearchService, useValue: new SearchServiceStub(searchLink) }, { provide: ActivatedRoute, useValue: route }, diff --git a/src/app/shared/search/search-labels/search-label/search-label.component.ts b/src/app/shared/search/search-labels/search-label/search-label.component.ts index 22c63c71c35..b061f684a6b 100644 --- a/src/app/shared/search/search-labels/search-label/search-label.component.ts +++ b/src/app/shared/search/search-labels/search-label/search-label.component.ts @@ -1,6 +1,7 @@ import { AsyncPipe } from '@angular/common'; import { Component, + Inject, Input, OnInit, } from '@angular/core'; @@ -16,6 +17,7 @@ import { PaginationService } from '../../../../core/pagination/pagination.servic import { SearchService } from '../../../../core/shared/search/search.service'; import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service'; import { SearchFilterService } from '../../../../core/shared/search/search-filter.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../../my-dspace-page/my-dspace-configuration.service'; import { currentPath } from '../../../utils/route.utils'; import { AppliedFilter } from '../../models/applied-filter.model'; @@ -45,7 +47,7 @@ export class SearchLabelComponent implements OnInit { constructor( protected paginationService: PaginationService, protected router: Router, - protected searchConfigurationService: SearchConfigurationService, + @Inject(SEARCH_CONFIG_SERVICE) protected searchConfigurationService: SearchConfigurationService, protected searchService: SearchService, protected searchFilterService: SearchFilterService, ) { From 11357916cbabe5ff213fd1f20069fe49d71eaf55 Mon Sep 17 00:00:00 2001 From: Ali Jaber Date: Sun, 2 Aug 2026 18:56:57 -0400 Subject: [PATCH 4/9] 143851: isolate parameters for unique search instances --- .../search-configuration.service.spec.ts | 79 +++++++++++++++++++ .../search/search-configuration.service.ts | 64 +++++++++++++-- .../search/search-filter.service.spec.ts | 35 ++++++++ .../shared/search/search-filter.service.ts | 44 +++++++---- .../search/search-instance-id.service.spec.ts | 28 +++++++ .../search/search-instance-id.service.ts | 40 ++++++++++ .../core/shared/search/search.service.spec.ts | 27 +++++++ src/app/core/shared/search/search.service.ts | 5 +- .../search-form/search-form.component.spec.ts | 4 +- .../search-form/search-form.component.ts | 4 +- .../search-facet-option.component.spec.ts | 14 ++++ .../search-facet-option.component.ts | 7 +- ...earch-facet-range-option.component.spec.ts | 1 + .../search-facet-range-option.component.ts | 7 +- .../search-range-filter.component.spec.ts | 12 +++ .../search-range-filter.component.ts | 22 ++++-- .../shared/search/search.component.spec.ts | 37 ++++++++- src/app/shared/search/search.component.ts | 22 ++++-- .../search-configuration-service.stub.ts | 2 + .../testing/search-filter-service.stub.ts | 12 +-- .../configuration-search-page.component.ts | 6 ++ .../app/search-page/search-page.component.ts | 6 ++ .../search-filters.component.ts | 8 -- .../search-settings.component.ts | 8 -- .../search-sidebar.component.ts | 8 -- 25 files changed, 428 insertions(+), 74 deletions(-) create mode 100644 src/app/core/shared/search/search-instance-id.service.spec.ts create mode 100644 src/app/core/shared/search/search-instance-id.service.ts diff --git a/src/app/core/shared/search/search-configuration.service.spec.ts b/src/app/core/shared/search/search-configuration.service.spec.ts index 672dab026d0..817dab018db 100644 --- a/src/app/core/shared/search/search-configuration.service.spec.ts +++ b/src/app/core/shared/search/search-configuration.service.spec.ts @@ -15,6 +15,7 @@ import { AppliedFilter } from '../../../shared/search/models/applied-filter.mode import { PaginatedSearchOptions } from '../../../shared/search/models/paginated-search-options.model'; import { SearchFilter } from '../../../shared/search/models/search-filter.model'; import { SearchObjects } from '../../../shared/search/models/search-objects.model'; +import { SearchOptions } from '../../../shared/search/models/search-options.model'; import { ActivatedRouteStub } from '../../../shared/testing/active-router.stub'; import { PaginationServiceStub } from '../../../shared/testing/pagination-service.stub'; import { @@ -83,6 +84,9 @@ describe('SearchConfigurationService', () => { }, }; beforeEach(() => { + routeService.getQueryParameterValue.and.returnValue(of(value1)); + routeService.getQueryParamsWithPrefix.and.returnValue(of(prefixFilter)); + routeService.getRouteParameterValue.and.returnValue(of('')); paginationService = new PaginationServiceStub(Object.assign(new PaginationComponentOptions(), { id: defaults.pagination.id, currentPage: 1, @@ -323,6 +327,81 @@ describe('SearchConfigurationService', () => { }); }); + describe('with legacy search parameter fallback disabled', () => { + beforeEach(() => { + service.useLegacySearchParamFallback = false; + routeService.getQueryParameterValue.calls.reset(); + routeService.getQueryParamsWithPrefix.calls.reset(); + routeService.getRouteParameterValue.calls.reset(); + }); + + it('should read only the prefixed query parameter', (done: DoneFn) => { + routeService.getQueryParameterValue.and.callFake((param: string) => + of(param === `${defaults.pagination.id}.query` ? 'instance query' : 'legacy query')); + + service.getCurrentQuery('').subscribe((query: string) => { + expect(query).toBe('instance query'); + expect(routeService.getQueryParameterValue).not.toHaveBeenCalledWith('query'); + done(); + }); + }); + + it('should read only prefixed configuration parameters', (done: DoneFn) => { + routeService.getQueryParameterValue.and.callFake((param: string) => + of(param === `${defaults.pagination.id}.configuration` ? 'instance configuration' : 'legacy configuration')); + routeService.getRouteParameterValue.and.returnValue(of(undefined)); + + service.getCurrentConfiguration('default').subscribe((configuration: string) => { + expect(configuration).toBe('instance configuration'); + expect(routeService.getQueryParameterValue).not.toHaveBeenCalledWith('configuration'); + expect(routeService.getRouteParameterValue).not.toHaveBeenCalledWith('configuration'); + done(); + }); + }); + + it('should read only prefixed frontend filters', (done: DoneFn) => { + const instanceFilters = { + [`${defaults.pagination.id}.f.author`]: ['instance author'], + }; + routeService.getQueryParamsWithPrefix.and.callFake((prefix: string) => + of(prefix === `${defaults.pagination.id}.f.` ? instanceFilters : prefixFilter)); + + service.getCurrentFrontendFilters().subscribe((filters: Params) => { + expect(filters).toEqual(instanceFilters); + expect(routeService.getQueryParamsWithPrefix).not.toHaveBeenCalledWith('f.'); + done(); + }); + }); + + it('should read only the prefixed fixed filter route parameter', (done: DoneFn) => { + routeService.getRouteParameterValue.and.callFake((param: string) => + of(param === `${defaults.pagination.id}.fixedFilterQuery` ? 'instance fixed filter' : 'legacy fixed filter')); + + service.getCurrentFixedFilter().subscribe((fixedFilter: string) => { + expect(fixedFilter).toBe('instance fixed filter'); + expect(routeService.getRouteParameterValue).not.toHaveBeenCalledWith('fixedFilterQuery'); + done(); + }); + }); + + it('should discard state previously derived from legacy parameters when changing instance id', () => { + service.searchOptions.next(Object.assign(new SearchOptions({}), service.searchOptions.value, { query: 'legacy query' })); + service.paginatedSearchOptions.next(Object.assign( + new PaginatedSearchOptions({}), + service.paginatedSearchOptions.value, + { query: 'legacy query' }, + )); + routeService.getQueryParameterValue.and.returnValue(of(undefined)); + routeService.getQueryParamsWithPrefix.and.returnValue(of({})); + routeService.getRouteParameterValue.and.returnValue(of(undefined)); + + service.setSearchInstanceId('strict-id'); + + expect(service.searchOptions.value.query).toBe(''); + expect(service.paginatedSearchOptions.value.query).toBe(''); + }); + }); + describe('unselectAppliedFilterParams', () => { let appliedFilter: AppliedFilter; diff --git a/src/app/core/shared/search/search-configuration.service.ts b/src/app/core/shared/search/search-configuration.service.ts index a2b3aa94039..0581fe98e04 100644 --- a/src/app/core/shared/search/search-configuration.service.ts +++ b/src/app/core/shared/search/search-configuration.service.ts @@ -89,6 +89,13 @@ export class SearchConfigurationService implements OnDestroy { */ public searchInstanceId = 'spc'; + /** + * Whether unprefixed search parameters should be used when this search instance has no + * corresponding prefixed parameter. Unique search instances disable this fallback so they + * cannot consume parameters that belong to another search on the same page. + */ + public useLegacySearchParamFallback = true; + /** * The names of the query parameters that are scoped to a search instance, but that still accept a * legacy (unprefixed) value for backwards compatibility. Filter parameters (prefixed with `f.`) are @@ -130,6 +137,12 @@ export class SearchConfigurationService implements OnDestroy { */ protected _defaults: Observable>; + /** + * The original unmodified defaults, used to clear any legacy-derived state when an instance + * switches to strict prefixed parameters. + */ + protected initialSearchOptions: PaginatedSearchOptions; + /** * A map of subscriptions to unsubscribe from on destroy */ @@ -166,13 +179,28 @@ export class SearchConfigurationService implements OnDestroy { * @returns {Observable} Emits the current configuration string */ getCurrentConfiguration(defaultConfiguration: string, searchInstanceId = this.searchInstanceId) { + const instanceQueryConfiguration$ = this.routeService + .getQueryParameterValue(this.getSearchInstanceParam(searchInstanceId, 'configuration')); + const instanceRouteConfiguration$ = this.routeService + .getRouteParameterValue(this.getSearchInstanceParam(searchInstanceId, 'configuration')); + const instanceConfiguration$ = observableCombineLatest([ + instanceQueryConfiguration$, + instanceRouteConfiguration$, + ]); + if (!this.useLegacySearchParamFallback) { + return instanceConfiguration$.pipe( + map(([instanceQueryConfig, instanceRouteConfig]) => instanceQueryConfig || instanceRouteConfig || defaultConfiguration), + ); + } return observableCombineLatest([ - this.routeService.getQueryParameterValue(this.getSearchInstanceParam(searchInstanceId, 'configuration')).pipe(startWith(undefined)), - this.routeService.getRouteParameterValue(this.getSearchInstanceParam(searchInstanceId, 'configuration')).pipe(startWith(undefined)), + observableCombineLatest([ + instanceQueryConfiguration$.pipe(startWith(undefined)), + instanceRouteConfiguration$.pipe(startWith(undefined)), + ]), this.routeService.getQueryParameterValue('configuration').pipe(startWith(undefined)), this.routeService.getRouteParameterValue('configuration').pipe(startWith(undefined)), ]).pipe( - map(([instanceQueryConfig, instanceRouteConfig, queryConfig, routeConfig]) => { + map(([[instanceQueryConfig, instanceRouteConfig], queryConfig, routeConfig]) => { return instanceQueryConfig || instanceRouteConfig || queryConfig || routeConfig || defaultConfiguration; }), ); @@ -249,8 +277,13 @@ export class SearchConfigurationService implements OnDestroy { * @returns {Observable} Emits the current fixed filter as a string */ getCurrentFixedFilter(searchInstanceId = this.searchInstanceId): Observable { + const instanceFixedFilter$ = this.routeService + .getRouteParameterValue(this.getSearchInstanceParam(searchInstanceId, 'fixedFilterQuery')); + if (!this.useLegacySearchParamFallback) { + return instanceFixedFilter$; + } return observableCombineLatest([ - this.routeService.getRouteParameterValue(this.getSearchInstanceParam(searchInstanceId, 'fixedFilterQuery')).pipe(startWith(undefined)), + instanceFixedFilter$.pipe(startWith(undefined)), this.routeService.getRouteParameterValue('fixedFilterQuery').pipe(startWith(undefined)), ]).pipe( map(([instanceFixedFilter, fixedFilter]) => instanceFixedFilter || fixedFilter), @@ -261,8 +294,13 @@ export class SearchConfigurationService implements OnDestroy { * @returns {Observable} Emits the current active filters with their values as they are displayed in the frontend URL */ getCurrentFrontendFilters(searchInstanceId = this.searchInstanceId): Observable { + const instanceFilters$ = this.routeService + .getQueryParamsWithPrefix(this.getSearchInstanceFilterParamPrefix(searchInstanceId)); + if (!this.useLegacySearchParamFallback) { + return instanceFilters$; + } return observableCombineLatest([ - this.routeService.getQueryParamsWithPrefix(this.getSearchInstanceFilterParamPrefix(searchInstanceId)).pipe(startWith({})), + instanceFilters$.pipe(startWith({})), this.routeService.getQueryParamsWithPrefix('f.').pipe(startWith({})), ]).pipe(map(([instanceFilters, legacyFilters]) => { return isNotEmpty(instanceFilters) ? instanceFilters : legacyFilters; @@ -319,8 +357,9 @@ export class SearchConfigurationService implements OnDestroy { setSearchInstanceId(searchInstanceId): void { if (isNotEmpty(searchInstanceId)) { const currentValue: PaginatedSearchOptions = this.paginatedSearchOptions.getValue(); - const updatedValue: PaginatedSearchOptions = Object.assign(new PaginatedSearchOptions({}), currentValue, { - pagination: Object.assign({}, currentValue.pagination, { + const defaults = this.useLegacySearchParamFallback ? currentValue : this.initialSearchOptions; + const updatedValue: PaginatedSearchOptions = Object.assign(new PaginatedSearchOptions({}), defaults, { + pagination: Object.assign({}, defaults.pagination, { id: searchInstanceId, }), }); @@ -329,6 +368,9 @@ export class SearchConfigurationService implements OnDestroy { // change to the new search instance id this.searchInstanceId = searchInstanceId; + if (!this.useLegacySearchParamFallback) { + this.searchOptions.next(Object.assign(new SearchOptions({}), updatedValue)); + } this.paginatedSearchOptions.next(updatedValue); this.setSearchSubscription(this.searchInstanceId, this.paginatedSearchOptions.value); } @@ -372,8 +414,13 @@ export class SearchConfigurationService implements OnDestroy { } private getCurrentSearchInstanceQueryParam(searchInstanceId: string, parameterName: string): Observable { + const instanceValue$ = this.routeService + .getQueryParameterValue(this.getSearchInstanceParam(searchInstanceId, parameterName)); + if (!this.useLegacySearchParamFallback) { + return instanceValue$; + } return observableCombineLatest([ - this.routeService.getQueryParameterValue(this.getSearchInstanceParam(searchInstanceId, parameterName)).pipe(startWith(undefined)), + instanceValue$.pipe(startWith(undefined)), this.routeService.getQueryParameterValue(parameterName).pipe(startWith(undefined)), ]).pipe( map(([instanceValue, legacyValue]) => hasValue(instanceValue) ? instanceValue : legacyValue), @@ -411,6 +458,7 @@ export class SearchConfigurationService implements OnDestroy { .pipe(getFirstSucceededRemoteData()) .subscribe((defRD: RemoteData) => { const defs = defRD.payload; + this.initialSearchOptions = defs; this.paginatedSearchOptions = new BehaviorSubject(defs); this.searchOptions = new BehaviorSubject(defs); this.setSearchSubscription(this.searchInstanceId, defs); diff --git a/src/app/core/shared/search/search-filter.service.spec.ts b/src/app/core/shared/search/search-filter.service.spec.ts index af354f87dfc..a19917d6810 100644 --- a/src/app/core/shared/search/search-filter.service.spec.ts +++ b/src/app/core/shared/search/search-filter.service.spec.ts @@ -255,6 +255,41 @@ describe('SearchFilterService', () => { }); }); + describe('when legacy fallback is disabled for a search instance', () => { + const searchInstanceId = 'spc1'; + + it('should check only the prefixed filter value', (done: DoneFn) => { + const hasQueryParamWithValue = spyOn(routeServiceStub, 'hasQueryParamWithValue').and.returnValue(of(true)); + + service.isFilterActiveWithValue('f.author', value1, searchInstanceId, false).subscribe((active: boolean) => { + expect(active).toBeTrue(); + expect(hasQueryParamWithValue).toHaveBeenCalledOnceWith(`${searchInstanceId}.f.author`, value1); + done(); + }); + }); + + it('should read only the prefixed query', (done: DoneFn) => { + const getQueryParameterValue = spyOn(routeServiceStub, 'getQueryParameterValue').and.returnValue(of('instance query')); + + service.getCurrentQuery(searchInstanceId, false).subscribe((query: string) => { + expect(query).toBe('instance query'); + expect(getQueryParameterValue).toHaveBeenCalledOnceWith(`${searchInstanceId}.query`); + done(); + }); + }); + + it('should read only the prefixed filters', (done: DoneFn) => { + const instanceFilters = { [`${searchInstanceId}.f.author`]: [value1] }; + const getQueryParamsWithPrefix = spyOn(routeServiceStub, 'getQueryParamsWithPrefix').and.returnValue(of(instanceFilters)); + + service.getCurrentFilters(searchInstanceId, false).subscribe((filters) => { + expect(filters).toEqual(instanceFilters); + expect(getQueryParamsWithPrefix).toHaveBeenCalledOnceWith(`${searchInstanceId}.f.`); + done(); + }); + }); + }); + describe('when findSuggestions is called with query \'test\'', () => { const query = 'test'; diff --git a/src/app/core/shared/search/search-filter.service.ts b/src/app/core/shared/search/search-filter.service.ts index 506f76fd264..a36b593b876 100644 --- a/src/app/core/shared/search/search-filter.service.ts +++ b/src/app/core/shared/search/search-filter.service.ts @@ -74,10 +74,14 @@ export class SearchFilterService { * @param {string} filterValue The value for which to search * @returns {Observable} Emit true when the filter is active with the given value */ - isFilterActiveWithValue(paramName: string, filterValue: string, searchInstanceId?: string): Observable { + isFilterActiveWithValue(paramName: string, filterValue: string, searchInstanceId?: string, useLegacySearchParamFallback = true): Observable { if (hasValue(searchInstanceId)) { + const instanceActive$ = this.routeService.hasQueryParamWithValue(this.getSearchInstanceParam(searchInstanceId, paramName), filterValue); + if (!useLegacySearchParamFallback) { + return instanceActive$; + } return observableCombineLatest( - this.routeService.hasQueryParamWithValue(this.getSearchInstanceParam(searchInstanceId, paramName), filterValue), + instanceActive$, this.routeService.getQueryParamsWithPrefix(this.getSearchInstanceParam(searchInstanceId, 'f.')), this.routeService.hasQueryParamWithValue(paramName, filterValue), ).pipe(map(([instanceActive, instanceFilters, legacyActive]) => instanceActive || (!isNotEmpty(instanceFilters) && legacyActive))); @@ -90,10 +94,14 @@ export class SearchFilterService { * @param {string} paramName The parameter name of the filter's configuration for which to search * @returns {Observable} Emit true when the filter is active with any value */ - isFilterActive(paramName: string, searchInstanceId?: string): Observable { + isFilterActive(paramName: string, searchInstanceId?: string, useLegacySearchParamFallback = true): Observable { if (hasValue(searchInstanceId)) { + const instanceActive$ = this.routeService.hasQueryParam(this.getSearchInstanceParam(searchInstanceId, paramName)); + if (!useLegacySearchParamFallback) { + return instanceActive$; + } return observableCombineLatest( - this.routeService.hasQueryParam(this.getSearchInstanceParam(searchInstanceId, paramName)), + instanceActive$, this.routeService.getQueryParamsWithPrefix(this.getSearchInstanceParam(searchInstanceId, 'f.')), this.routeService.hasQueryParam(paramName), ).pipe(map(([instanceActive, instanceFilters, legacyActive]) => instanceActive || (!isNotEmpty(instanceFilters) && legacyActive))); @@ -105,16 +113,16 @@ export class SearchFilterService { * Fetch the current active scope from the query parameters * @returns {Observable} */ - getCurrentScope(searchInstanceId?: string) { - return this.getCurrentSearchInstanceQueryParam(searchInstanceId, 'scope'); + getCurrentScope(searchInstanceId?: string, useLegacySearchParamFallback = true) { + return this.getCurrentSearchInstanceQueryParam(searchInstanceId, 'scope', useLegacySearchParamFallback); } /** * Fetch the current query from the query parameters * @returns {Observable} */ - getCurrentQuery(searchInstanceId?: string) { - return this.getCurrentSearchInstanceQueryParam(searchInstanceId, 'query'); + getCurrentQuery(searchInstanceId?: string, useLegacySearchParamFallback = true) { + return this.getCurrentSearchInstanceQueryParam(searchInstanceId, 'query', useLegacySearchParamFallback); } /** @@ -155,10 +163,14 @@ export class SearchFilterService { * Fetch the current active filters from the query parameters * @returns {Observable} */ - getCurrentFilters(searchInstanceId?: string) { + getCurrentFilters(searchInstanceId?: string, useLegacySearchParamFallback = true) { if (hasValue(searchInstanceId)) { + const instanceFilters$ = this.routeService.getQueryParamsWithPrefix(this.getSearchInstanceParam(searchInstanceId, 'f.')); + if (!useLegacySearchParamFallback) { + return instanceFilters$; + } return observableCombineLatest( - this.routeService.getQueryParamsWithPrefix(this.getSearchInstanceParam(searchInstanceId, 'f.')), + instanceFilters$, this.routeService.getQueryParamsWithPrefix('f.'), ).pipe(map(([instanceFilters, legacyFilters]) => isNotEmpty(instanceFilters) ? instanceFilters : legacyFilters)); } @@ -169,8 +181,8 @@ export class SearchFilterService { * Fetch the current view from the query parameters * @returns {Observable} */ - getCurrentView(searchInstanceId?: string) { - return this.getCurrentSearchInstanceQueryParam(searchInstanceId, 'view'); + getCurrentView(searchInstanceId?: string, useLegacySearchParamFallback = true) { + return this.getCurrentSearchInstanceQueryParam(searchInstanceId, 'view', useLegacySearchParamFallback); } /** @@ -213,10 +225,14 @@ export class SearchFilterService { return `${searchInstanceId}.${parameterName}`; } - private getCurrentSearchInstanceQueryParam(searchInstanceId: string | undefined, parameterName: string): Observable { + private getCurrentSearchInstanceQueryParam(searchInstanceId: string | undefined, parameterName: string, useLegacySearchParamFallback: boolean): Observable { if (hasValue(searchInstanceId)) { + const instanceValue$ = this.routeService.getQueryParameterValue(this.getSearchInstanceParam(searchInstanceId, parameterName)); + if (!useLegacySearchParamFallback) { + return instanceValue$; + } return observableCombineLatest( - this.routeService.getQueryParameterValue(this.getSearchInstanceParam(searchInstanceId, parameterName)), + instanceValue$, this.routeService.getQueryParameterValue(parameterName), ).pipe(map(([instanceValue, legacyValue]) => hasValue(instanceValue) ? instanceValue : legacyValue)); } diff --git a/src/app/core/shared/search/search-instance-id.service.spec.ts b/src/app/core/shared/search/search-instance-id.service.spec.ts new file mode 100644 index 00000000000..35b411eb280 --- /dev/null +++ b/src/app/core/shared/search/search-instance-id.service.spec.ts @@ -0,0 +1,28 @@ +import { SearchInstanceIdService } from './search-instance-id.service'; + +describe('SearchInstanceIdService', () => { + let service: SearchInstanceIdService; + + beforeEach(() => { + service = new SearchInstanceIdService(); + }); + + it('should allocate unique ids for active search instances', () => { + expect(service.acquire('spc')).toBe('spc1'); + expect(service.acquire('spc')).toBe('spc2'); + }); + + it('should reuse a released id', () => { + const firstId = service.acquire('spc'); + service.acquire('spc'); + + service.release('spc', firstId); + + expect(service.acquire('spc')).toBe('spc1'); + }); + + it('should allocate ids independently for different bases', () => { + expect(service.acquire('spc')).toBe('spc1'); + expect(service.acquire('related')).toBe('related1'); + }); +}); diff --git a/src/app/core/shared/search/search-instance-id.service.ts b/src/app/core/shared/search/search-instance-id.service.ts new file mode 100644 index 00000000000..e340dadd779 --- /dev/null +++ b/src/app/core/shared/search/search-instance-id.service.ts @@ -0,0 +1,40 @@ +import { Injectable } from '@angular/core'; + +/** + * Allocates unique search instance ids and reuses them after a search component is destroyed. + * + * Reusing released ids keeps URL parameter prefixes stable when Angular recreates all search + * components after a query-parameter navigation. + */ +@Injectable({ providedIn: 'root' }) +export class SearchInstanceIdService { + + private readonly allocatedIds: Map> = new Map>(); + + acquire(baseId: string): string { + const allocatedForBase = this.allocatedIds.get(baseId) ?? new Set(); + let suffix = 1; + while (allocatedForBase.has(suffix)) { + suffix++; + } + allocatedForBase.add(suffix); + this.allocatedIds.set(baseId, allocatedForBase); + return `${baseId}${suffix}`; + } + + release(baseId: string, instanceId: string): void { + if (!instanceId.startsWith(baseId)) { + return; + } + const suffix = Number(instanceId.substring(baseId.length)); + if (!Number.isInteger(suffix) || suffix < 1) { + return; + } + const allocatedForBase = this.allocatedIds.get(baseId); + allocatedForBase?.delete(suffix); + if (allocatedForBase?.size === 0) { + this.allocatedIds.delete(baseId); + } + } + +} diff --git a/src/app/core/shared/search/search.service.spec.ts b/src/app/core/shared/search/search.service.spec.ts index 6a6ac68837c..63db44c5a9b 100644 --- a/src/app/core/shared/search/search.service.spec.ts +++ b/src/app/core/shared/search/search.service.spec.ts @@ -139,6 +139,33 @@ describe('SearchService', () => { }); }); }); + + it('should ignore a legacy view mode when fallback is disabled', () => { + searchConfigService.useLegacySearchParamFallback = false; + spyOn(routeService, 'getQueryParamMap').and.returnValue(of(new Map([ + ['view', ViewMode.GridElement], + ]))); + + testScheduler.run(({ expectObservable }) => { + expectObservable(service.getViewMode()).toBe('(a|)', { + a: ViewMode.ListElement, + }); + }); + }); + + it('should use the prefixed view mode when fallback is disabled', () => { + searchConfigService.useLegacySearchParamFallback = false; + spyOn(routeService, 'getQueryParamMap').and.returnValue(of(new Map([ + [`${searchConfigService.searchInstanceId}.view`, ViewMode.GridElement], + ['view', ViewMode.ListElement], + ]))); + + testScheduler.run(({ expectObservable }) => { + expectObservable(service.getViewMode()).toBe('(a|)', { + a: ViewMode.GridElement, + }); + }); + }); }); describe('search', () => { diff --git a/src/app/core/shared/search/search.service.ts b/src/app/core/shared/search/search.service.ts index 50d2dae3b90..915a6a61806 100644 --- a/src/app/core/shared/search/search.service.ts +++ b/src/app/core/shared/search/search.service.ts @@ -343,7 +343,10 @@ export class SearchService { getViewMode(): Observable { return this.routeService.getQueryParamMap().pipe(map((params) => { const viewParam = this.searchConfigurationService.getCurrentSearchInstanceParam('view'); - const view = hasValue(params.get(viewParam)) ? params.get(viewParam) : params.get('view'); + const instanceView = params.get(viewParam); + const view = hasValue(instanceView) || !this.searchConfigurationService.useLegacySearchParamFallback + ? instanceView + : params.get('view'); if (isNotEmpty(view) && hasValue(view)) { return view; } else { diff --git a/src/app/shared/search-form/search-form.component.spec.ts b/src/app/shared/search-form/search-form.component.spec.ts index 81c7950175c..e94c4fa944c 100644 --- a/src/app/shared/search-form/search-form.component.spec.ts +++ b/src/app/shared/search-form/search-form.component.spec.ts @@ -17,8 +17,8 @@ import { PaginationService } from '../../core/pagination/pagination.service'; import { Community } from '../../core/shared/community.model'; import { DSpaceObject } from '../../core/shared/dspace-object.model'; import { SearchService } from '../../core/shared/search/search.service'; -import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service'; import { SearchFilterService } from '../../core/shared/search/search-filter.service'; +import { SEARCH_CONFIG_SERVICE } from '../../my-dspace-page/my-dspace-configuration.service'; import { createSuccessfulRemoteDataObject$ } from '../remote-data.utils'; import { PaginationServiceStub } from '../testing/pagination-service.stub'; import { RouterStub } from '../testing/router.stub'; @@ -53,7 +53,7 @@ describe('SearchFormComponent', () => { { provide: SearchService, useValue: searchService }, { provide: SearchFilterService, useValue: searchFilterService }, { provide: PaginationService, useValue: paginationService }, - { provide: SearchConfigurationService, useValue: searchConfigService }, + { provide: SEARCH_CONFIG_SERVICE, useValue: searchConfigService }, { provide: DSpaceObjectDataService, useValue: dspaceObjectService }, ], }).compileComponents(); diff --git a/src/app/shared/search-form/search-form.component.ts b/src/app/shared/search-form/search-form.component.ts index 591972e089d..0f9693ae386 100644 --- a/src/app/shared/search-form/search-form.component.ts +++ b/src/app/shared/search-form/search-form.component.ts @@ -2,6 +2,7 @@ import { AsyncPipe } from '@angular/common'; import { Component, EventEmitter, + Inject, Input, OnChanges, Output, @@ -27,6 +28,7 @@ import { getFirstSucceededRemoteDataPayload } from '../../core/shared/operators' import { SearchService } from '../../core/shared/search/search.service'; import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service'; import { SearchFilterService } from '../../core/shared/search/search-filter.service'; +import { SEARCH_CONFIG_SERVICE } from '../../my-dspace-page/my-dspace-configuration.service'; import { hasValue, isNotEmpty, @@ -106,7 +108,7 @@ export class SearchFormComponent implements OnChanges { protected searchService: SearchService, protected searchFilterService: SearchFilterService, protected paginationService: PaginationService, - protected searchConfig: SearchConfigurationService, + @Inject(SEARCH_CONFIG_SERVICE) protected searchConfig: SearchConfigurationService, protected modalService: NgbModal, protected dsoService: DSpaceObjectDataService, public dsoNameService: DSONameService, diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.spec.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.spec.ts index d7e92f35e98..d3854c4c51f 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.spec.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.spec.ts @@ -102,6 +102,20 @@ describe('SearchFacetOptionComponent', () => { fixture.detectChanges(); }); + it('should pass strict fallback behavior to the filter service', () => { + searchConfigurationService.useLegacySearchParamFallback = false; + const isFilterActiveWithValue = spyOn(searchFilterService, 'isFilterActiveWithValue').and.returnValue(of(false)); + + comp.isChecked().subscribe(); + + expect(isFilterActiveWithValue).toHaveBeenCalledWith( + mockFilterConfig.paramName, + comp.getFacetValue(), + comp.searchInstanceId, + false, + ); + }); + describe('when isVisible emits true', () => { it('the facet option should be visible', () => { comp.isVisible = of(true); diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts index 959ec8c5f6f..9aa5de6224f 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts @@ -101,7 +101,12 @@ export class SearchFacetOptionComponent implements OnInit { * Checks if a value for this filter is currently active */ isChecked(): Observable { - return this.filterService.isFilterActiveWithValue(this.filterConfig.paramName, this.getFacetValue(), this.searchInstanceId); + return this.filterService.isFilterActiveWithValue( + this.filterConfig.paramName, + this.getFacetValue(), + this.searchInstanceId, + this.searchConfigService.useLegacySearchParamFallback, + ); } /** diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts index 9571b785b5b..eb1fafeb24c 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts @@ -83,6 +83,7 @@ describe('SearchFacetRangeOptionComponent', () => { provide: SEARCH_CONFIG_SERVICE, useValue: { searchOptions: of({}), searchInstanceId: 'page-id', + useLegacySearchParamFallback: true, getCurrentSearchInstanceFilterParam: (param: string) => `page-id.${param}`, }, }, diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.ts index 988d489953e..21cb05f8d8a 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.ts @@ -108,7 +108,12 @@ export class SearchFacetRangeOptionComponent implements OnInit, OnDestroy { * Checks if a value for this filter is currently active */ private isChecked(): Observable { - return this.filterService.isFilterActiveWithValue(this.filterConfig.paramName, this.filterValue.value, this.searchConfigService.searchInstanceId); + return this.filterService.isFilterActiveWithValue( + this.filterConfig.paramName, + this.filterValue.value, + this.searchConfigService.searchInstanceId, + this.searchConfigService.useLegacySearchParamFallback, + ); } /** diff --git a/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.spec.ts b/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.spec.ts index ba46e87f5e6..65facb12da9 100644 --- a/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.spec.ts +++ b/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.spec.ts @@ -136,6 +136,18 @@ describe('SearchRangeFilterComponent', () => { fixture.detectChanges(); }); + it('should ignore legacy range parameters when fallback is disabled', () => { + const getQueryParameterValue = spyOn(routeServiceStub, 'getQueryParameterValue').and.returnValue(of(undefined)); + comp.searchConfigService.useLegacySearchParamFallback = false; + + comp.ngOnInit(); + + expect(getQueryParameterValue).toHaveBeenCalledWith(`test-id.${mockFilterConfig.paramName}${minSuffix}`); + expect(getQueryParameterValue).toHaveBeenCalledWith(`test-id.${mockFilterConfig.paramName}${maxSuffix}`); + expect(getQueryParameterValue).not.toHaveBeenCalledWith(`${mockFilterConfig.paramName}${minSuffix}`); + expect(getQueryParameterValue).not.toHaveBeenCalledWith(`${mockFilterConfig.paramName}${maxSuffix}`); + }); + describe('when the onSubmit method is called with data', () => { const searchUrl = '/search/path'; // const data = { [mockFilterConfig.paramName + minSuffix]: '1900', [mockFilterConfig.paramName + maxSuffix]: '1950' }; diff --git a/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.ts b/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.ts index 1eae352716d..b2d481c2d22 100644 --- a/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.ts +++ b/src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.ts @@ -135,14 +135,20 @@ export class SearchRangeFilterComponent extends SearchFacetFilterComponent imple this.minLabel = this.translateService.instant('search.filters.filter.' + this.filterConfig.name + '.min.placeholder'); this.maxLabel = this.translateService.instant('search.filters.filter.' + this.filterConfig.name + '.max.placeholder'); const filterParamName = this.searchConfigService.getCurrentSearchInstanceFilterParam(this.filterConfig.paramName); - const iniMin = observableCombineLatest([ - this.route.getQueryParameterValue(filterParamName + RANGE_FILTER_MIN_SUFFIX).pipe(startWith(undefined)), - this.route.getQueryParameterValue(this.filterConfig.paramName + RANGE_FILTER_MIN_SUFFIX).pipe(startWith(undefined)), - ]).pipe(map(([instanceMin, legacyMin]: [string, string]) => hasValue(instanceMin) ? instanceMin : legacyMin)); - const iniMax = observableCombineLatest([ - this.route.getQueryParameterValue(filterParamName + RANGE_FILTER_MAX_SUFFIX).pipe(startWith(undefined)), - this.route.getQueryParameterValue(this.filterConfig.paramName + RANGE_FILTER_MAX_SUFFIX).pipe(startWith(undefined)), - ]).pipe(map(([instanceMax, legacyMax]: [string, string]) => hasValue(instanceMax) ? instanceMax : legacyMax)); + const instanceMin$ = this.route.getQueryParameterValue(filterParamName + RANGE_FILTER_MIN_SUFFIX).pipe(startWith(undefined)); + const instanceMax$ = this.route.getQueryParameterValue(filterParamName + RANGE_FILTER_MAX_SUFFIX).pipe(startWith(undefined)); + const iniMin = this.searchConfigService.useLegacySearchParamFallback + ? observableCombineLatest([ + instanceMin$, + this.route.getQueryParameterValue(this.filterConfig.paramName + RANGE_FILTER_MIN_SUFFIX).pipe(startWith(undefined)), + ]).pipe(map(([instanceMin, legacyMin]: [string, string]) => hasValue(instanceMin) ? instanceMin : legacyMin)) + : instanceMin$; + const iniMax = this.searchConfigService.useLegacySearchParamFallback + ? observableCombineLatest([ + instanceMax$, + this.route.getQueryParameterValue(this.filterConfig.paramName + RANGE_FILTER_MAX_SUFFIX).pipe(startWith(undefined)), + ]).pipe(map(([instanceMax, legacyMax]: [string, string]) => hasValue(instanceMax) ? instanceMax : legacyMax)) + : instanceMax$; this.subs.push(observableCombineLatest([iniMin, iniMax]).pipe( map(([min, max]: [string, string]) => { const minimum = hasValue(min) ? Number(min) : this.min; diff --git a/src/app/shared/search/search.component.spec.ts b/src/app/shared/search/search.component.spec.ts index 03546364ed3..f10f8403757 100644 --- a/src/app/shared/search/search.component.spec.ts +++ b/src/app/shared/search/search.component.spec.ts @@ -306,7 +306,7 @@ describe('SearchComponent', () => { const expectedSearchOptions = Object.assign(paginatedSearchOptions$.value, { configuration: 'default', - scope: '', + scope: 'test-id', sort: sortOptionsList[0], }); expect(comp.currentConfiguration$).toBeObservable(cold('b', { @@ -350,6 +350,41 @@ describe('SearchComponent', () => { expect(comp.resultFound.emit).toHaveBeenCalledWith(expectedResults); })); + describe('unique search instances', () => { + beforeEach(() => { + comp.useUniquePageId = true; + }); + + it('should disable legacy fallback and skip legacy parameter migration', fakeAsync(() => { + const migrateLegacySearchParams = spyOn(comp as any, 'migrateLegacySearchParams'); + + fixture.detectChanges(); + tick(100); + + expect(comp.searchInstanceId).toBe(`${paginationId}1`); + expect(searchConfigurationServiceStub.useLegacySearchParamFallback).toBeFalse(); + expect(migrateLegacySearchParams).not.toHaveBeenCalled(); + })); + + it('should reuse its id after routing recreates the component', fakeAsync(() => { + fixture.detectChanges(); + tick(100); + const initialInstanceId = comp.searchInstanceId; + fixture.destroy(); + + fixture = TestBed.createComponent(SearchComponent); + comp = fixture.componentInstance; + comp.inPlaceSearch = false; + comp.searchInstanceId = paginationId; + comp.useUniquePageId = true; + spyOn((comp as any), 'getSearchOptions').and.returnValue(paginatedSearchOptions$.asObservable()); + fixture.detectChanges(); + tick(100); + + expect(comp.searchInstanceId).toBe(initialInstanceId); + })); + }); + describe('migrateLegacySearchParams', () => { let navigateSpy: jasmine.Spy; diff --git a/src/app/shared/search/search.component.ts b/src/app/shared/search/search.component.ts index 5024440f17c..fdbee270ffc 100644 --- a/src/app/shared/search/search.component.ts +++ b/src/app/shared/search/search.component.ts @@ -9,6 +9,7 @@ import { Component, EventEmitter, Inject, + inject, Input, OnDestroy, OnInit, @@ -21,7 +22,6 @@ import { Router, } from '@angular/router'; import { TranslateModule } from '@ngx-translate/core'; -import uniqueId from 'lodash/uniqueId'; import { BehaviorSubject, combineLatest, @@ -55,6 +55,7 @@ import { getFirstCompletedRemoteData } from '../../core/shared/operators'; import { SearchService } from '../../core/shared/search/search.service'; import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service'; import { SearchConfig } from '../../core/shared/search/search-filters/search-config.model'; +import { SearchInstanceIdService } from '../../core/shared/search/search-instance-id.service'; import { ViewMode } from '../../core/shared/view-mode.model'; import { SubmissionObject } from '../../core/submission/models/submission-object.model'; import { WorkspaceItem } from '../../core/submission/models/workspaceitem.model'; @@ -110,6 +111,10 @@ import { SearchConfigurationOption } from './search-switch-configuration/search- */ export class SearchComponent implements OnDestroy, OnInit { + private readonly searchInstanceIdService = inject(SearchInstanceIdService); + + private uniqueSearchInstanceBaseId: string; + /** * The list of available configuration options */ @@ -376,13 +381,15 @@ export class SearchComponent implements OnDestroy, OnInit { } if (this.useUniquePageId) { - // Create a unique search instance id related to this SearchComponent. - this.searchInstanceId = uniqueId(this.searchInstanceId); + // Allocate an id that can be reused if routing recreates this search component. + this.uniqueSearchInstanceBaseId = this.searchInstanceId; + this.searchInstanceId = this.searchInstanceIdService.acquire(this.uniqueSearchInstanceBaseId); } + this.searchConfigService.useLegacySearchParamFallback = !this.useUniquePageId; this.searchConfigService.setSearchInstanceId(this.searchInstanceId); - if (isPlatformBrowser(this.platformId)) { + if (isPlatformBrowser(this.platformId) && this.searchConfigService.useLegacySearchParamFallback) { this.migrateLegacySearchParams(); } @@ -393,9 +400,7 @@ export class SearchComponent implements OnDestroy, OnInit { this.routeService.setParameter(this.searchConfigService.getCurrentSearchInstanceParam('fixedFilterQuery'), this.fixedFilterQuery); } - this.currentScope$ = this.routeService.getQueryParameterValue('scope').pipe( - map((routeValue: string) => hasValue(routeValue) ? routeValue : this.scope ?? ''), - ); + this.currentScope$ = this.searchConfigService.getCurrentScope(this.scope ?? ''); this.isSidebarCollapsed$ = this.isSidebarCollapsed(); this.searchLink = this.getSearchLink(); @@ -499,6 +504,9 @@ export class SearchComponent implements OnDestroy, OnInit { */ ngOnDestroy(): void { this.subs.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe()); + if (hasValue(this.uniqueSearchInstanceBaseId)) { + this.searchInstanceIdService.release(this.uniqueSearchInstanceBaseId, this.searchInstanceId); + } } /** diff --git a/src/app/shared/testing/search-configuration-service.stub.ts b/src/app/shared/testing/search-configuration-service.stub.ts index 0c481f230e2..291b4d18c67 100644 --- a/src/app/shared/testing/search-configuration-service.stub.ts +++ b/src/app/shared/testing/search-configuration-service.stub.ts @@ -19,6 +19,8 @@ export class SearchConfigurationServiceStub { public searchInstanceId = 'test-id'; + public useLegacySearchParamFallback = true; + public searchOptions: BehaviorSubject = new BehaviorSubject(new SearchOptions({})); public paginatedSearchOptions: BehaviorSubject = new BehaviorSubject(new PaginatedSearchOptions({})); diff --git a/src/app/shared/testing/search-filter-service.stub.ts b/src/app/shared/testing/search-filter-service.stub.ts index 6600796e030..4fbe0999960 100644 --- a/src/app/shared/testing/search-filter-service.stub.ts +++ b/src/app/shared/testing/search-filter-service.stub.ts @@ -17,19 +17,19 @@ import { SearchFilterConfig } from '../search/models/search-filter-config.model' */ export class SearchFilterServiceStub { - isFilterActiveWithValue(_paramName: string, _filterValue: string): Observable { + isFilterActiveWithValue(_paramName: string, _filterValue: string, _searchInstanceId?: string, _useLegacySearchParamFallback = true): Observable { return of(true); } - isFilterActive(_paramName: string): Observable { + isFilterActive(_paramName: string, _searchInstanceId?: string, _useLegacySearchParamFallback = true): Observable { return of(true); } - getCurrentScope(): Observable { + getCurrentScope(_searchInstanceId?: string, _useLegacySearchParamFallback = true): Observable { return of(undefined); } - getCurrentQuery(): Observable { + getCurrentQuery(_searchInstanceId?: string, _useLegacySearchParamFallback = true): Observable { return of(undefined); } @@ -41,11 +41,11 @@ export class SearchFilterServiceStub { return of(new SortOptions('', SortDirection.ASC)); } - getCurrentFilters(): Observable { + getCurrentFilters(_searchInstanceId?: string, _useLegacySearchParamFallback = true): Observable { return of({}); } - getCurrentView(): Observable { + getCurrentView(_searchInstanceId?: string, _useLegacySearchParamFallback = true): Observable { return of(undefined); } diff --git a/src/themes/custom/app/search-page/configuration-search-page.component.ts b/src/themes/custom/app/search-page/configuration-search-page.component.ts index 0459148f941..09fe22d8721 100644 --- a/src/themes/custom/app/search-page/configuration-search-page.component.ts +++ b/src/themes/custom/app/search-page/configuration-search-page.component.ts @@ -8,6 +8,7 @@ import { } from '@angular/core'; import { TranslateModule } from '@ngx-translate/core'; +import { SearchService } from '../../../../app/core/shared/search/search.service'; import { SearchConfigurationService } from '../../../../app/core/shared/search/search-configuration.service'; import { SEARCH_CONFIG_SERVICE } from '../../../../app/my-dspace-page/my-dspace-configuration.service'; import { ConfigurationSearchPageComponent as BaseComponent } from '../../../../app/search-page/configuration-search-page.component'; @@ -32,6 +33,11 @@ import { ViewModeSwitchComponent } from '../../../../app/shared/view-mode-switch provide: SEARCH_CONFIG_SERVICE, useClass: SearchConfigurationService, }, + { + provide: SearchConfigurationService, + useExisting: SEARCH_CONFIG_SERVICE, + }, + SearchService, ], imports: [ AsyncPipe, diff --git a/src/themes/custom/app/search-page/search-page.component.ts b/src/themes/custom/app/search-page/search-page.component.ts index acad1440e1b..a73b52220a8 100644 --- a/src/themes/custom/app/search-page/search-page.component.ts +++ b/src/themes/custom/app/search-page/search-page.component.ts @@ -1,6 +1,7 @@ import { Component } from '@angular/core'; import { SEARCH_CONFIG_SERVICE } from 'src/app/my-dspace-page/my-dspace-configuration.service'; +import { SearchService } from '../../../../app/core/shared/search/search.service'; import { SearchConfigurationService } from '../../../../app/core/shared/search/search-configuration.service'; import { SearchPageComponent as BaseComponent } from '../../../../app/search-page/search-page.component'; import { ThemedSearchComponent } from '../../../../app/shared/search/themed-search.component'; @@ -15,6 +16,11 @@ import { ThemedSearchComponent } from '../../../../app/shared/search/themed-sear provide: SEARCH_CONFIG_SERVICE, useClass: SearchConfigurationService, }, + { + provide: SearchConfigurationService, + useExisting: SEARCH_CONFIG_SERVICE, + }, + SearchService, ], imports: [ ThemedSearchComponent, diff --git a/src/themes/custom/app/shared/search/search-filters/search-filters.component.ts b/src/themes/custom/app/shared/search/search-filters/search-filters.component.ts index fabd30867ab..76d64b2b9a2 100644 --- a/src/themes/custom/app/shared/search/search-filters/search-filters.component.ts +++ b/src/themes/custom/app/shared/search/search-filters/search-filters.component.ts @@ -4,8 +4,6 @@ import { RouterLink } from '@angular/router'; import { TranslateModule } from '@ngx-translate/core'; import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader'; -import { SearchConfigurationService } from '../../../../../../app/core/shared/search/search-configuration.service'; -import { SEARCH_CONFIG_SERVICE } from '../../../../../../app/my-dspace-page/my-dspace-configuration.service'; import { SearchFilterComponent } from '../../../../../../app/shared/search/search-filters/search-filter/search-filter.component'; import { SearchFiltersComponent as BaseComponent } from '../../../../../../app/shared/search/search-filters/search-filters.component'; @@ -15,12 +13,6 @@ import { SearchFiltersComponent as BaseComponent } from '../../../../../../app/s styleUrls: ['../../../../../../app/shared/search/search-filters/search-filters.component.scss'], // templateUrl: './search-filters.component.html', templateUrl: '../../../../../../app/shared/search/search-filters/search-filters.component.html', - providers: [ - { - provide: SEARCH_CONFIG_SERVICE, - useClass: SearchConfigurationService, - }, - ], imports: [ AsyncPipe, NgxSkeletonLoaderModule, diff --git a/src/themes/custom/app/shared/search/search-settings/search-settings.component.ts b/src/themes/custom/app/shared/search/search-settings/search-settings.component.ts index 2d360d98c50..a5c19632bd2 100644 --- a/src/themes/custom/app/shared/search/search-settings/search-settings.component.ts +++ b/src/themes/custom/app/shared/search/search-settings/search-settings.component.ts @@ -2,8 +2,6 @@ import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { TranslateModule } from '@ngx-translate/core'; -import { SearchConfigurationService } from '../../../../../../app/core/shared/search/search-configuration.service'; -import { SEARCH_CONFIG_SERVICE } from '../../../../../../app/my-dspace-page/my-dspace-configuration.service'; import { PageSizeSelectorComponent } from '../../../../../../app/shared/page-size-selector/page-size-selector.component'; import { SearchSettingsComponent as BaseComponent } from '../../../../../../app/shared/search/search-settings/search-settings.component'; import { SidebarDropdownComponent } from '../../../../../../app/shared/sidebar/sidebar-dropdown.component'; @@ -14,12 +12,6 @@ import { SidebarDropdownComponent } from '../../../../../../app/shared/sidebar/s styleUrls: ['../../../../../../app/shared/search/search-settings/search-settings.component.scss'], // templateUrl: './search-settings.component.html', templateUrl: '../../../../../../app/shared/search/search-settings/search-settings.component.html', - providers: [ - { - provide: SEARCH_CONFIG_SERVICE, - useClass: SearchConfigurationService, - }, - ], imports: [ FormsModule, PageSizeSelectorComponent, diff --git a/src/themes/custom/app/shared/search/search-sidebar/search-sidebar.component.ts b/src/themes/custom/app/shared/search/search-sidebar/search-sidebar.component.ts index c99ef57cfc4..d261e945d30 100644 --- a/src/themes/custom/app/shared/search/search-sidebar/search-sidebar.component.ts +++ b/src/themes/custom/app/shared/search/search-sidebar/search-sidebar.component.ts @@ -2,8 +2,6 @@ import { AsyncPipe } from '@angular/common'; import { Component } from '@angular/core'; import { TranslateModule } from '@ngx-translate/core'; -import { SearchConfigurationService } from '../../../../../../app/core/shared/search/search-configuration.service'; -import { SEARCH_CONFIG_SERVICE } from '../../../../../../app/my-dspace-page/my-dspace-configuration.service'; import { AdvancedSearchComponent } from '../../../../../../app/shared/search/advanced-search/advanced-search.component'; import { ThemedSearchFiltersComponent } from '../../../../../../app/shared/search/search-filters/themed-search-filters.component'; import { ThemedSearchSettingsComponent } from '../../../../../../app/shared/search/search-settings/themed-search-settings.component'; @@ -17,12 +15,6 @@ import { ViewModeSwitchComponent } from '../../../../../../app/shared/view-mode- styleUrls: ['../../../../../../app/shared/search/search-sidebar/search-sidebar.component.scss'], // templateUrl: './search-sidebar.component.html', templateUrl: '../../../../../../app/shared/search/search-sidebar/search-sidebar.component.html', - providers: [ - { - provide: SEARCH_CONFIG_SERVICE, - useClass: SearchConfigurationService, - }, - ], imports: [ AdvancedSearchComponent, AsyncPipe, From 44c02d65392879fa7e2ef42ad2a14d3198d88982 Mon Sep 17 00:00:00 2001 From: Ali Jaber Date: Wed, 12 Aug 2026 21:18:46 -0400 Subject: [PATCH 5/9] 143851: read prefixed search params outside SearchConfigurationService --- .../item-types/shared/item-iiif-utils.ts | 9 ++- .../geospatial-map.component.spec.ts | 7 +- .../geospatial-map.component.ts | 12 +++- .../object-collection.component.spec.ts | 69 +++++++++++++++++++ .../object-collection.component.ts | 12 +++- .../object-geospatial-map.component.spec.ts | 10 ++- src/app/shared/rss-feed/rss.component.spec.ts | 4 +- src/app/shared/rss-feed/rss.component.ts | 4 +- .../advanced-search.component.spec.ts | 4 +- .../advanced-search.component.ts | 3 +- .../search-label-range.component.spec.ts | 4 +- .../search-label-range.component.ts | 4 +- .../search-results.component.spec.ts | 8 +-- .../search-results.component.ts | 11 ++- .../search-sidebar.component.spec.ts | 4 +- .../search-sidebar.component.ts | 3 +- .../theme-support/theme.service.spec.ts | 50 ++++++++++++++ src/app/shared/theme-support/theme.service.ts | 21 +++++- 18 files changed, 205 insertions(+), 34 deletions(-) diff --git a/src/app/item-page/simple/item-types/shared/item-iiif-utils.ts b/src/app/item-page/simple/item-types/shared/item-iiif-utils.ts index 0c073272fe9..dd506ee2a2c 100644 --- a/src/app/item-page/simple/item-types/shared/item-iiif-utils.ts +++ b/src/app/item-page/simple/item-types/shared/item-iiif-utils.ts @@ -11,6 +11,7 @@ import { import { RouteService } from '../../../../core/services/route.service'; import { Item } from '../../../../core/shared/item.model'; +import { hasValue } from '../../../../shared/empty.util'; export const isIiifEnabled = (item: Item) => { return String(item.firstMetadataValue('dspace.iiif.enabled')?.valueOf?.() || '').trim().toLowerCase() === 'true'; @@ -37,7 +38,13 @@ export const getDSpaceQuery = (item: Item, routeService: RouteService): Observab }), map((r: string) => { const url: UrlTree = new DefaultUrlSerializer().parse(r); - return url.queryParamMap.get('query'); + const queryParamMap = url.queryParamMap; + const unprefixedQuery = queryParamMap.get('query'); + if (hasValue(unprefixedQuery)) { + return unprefixedQuery; + } + const prefixedKey = queryParamMap.keys.find((key: string) => key.endsWith('.query')); + return hasValue(prefixedKey) ? queryParamMap.get(prefixedKey) : null; }), take(1), ); diff --git a/src/app/shared/geospatial-map/geospatial-map.component.spec.ts b/src/app/shared/geospatial-map/geospatial-map.component.spec.ts index 447d8204e81..c8db221289d 100644 --- a/src/app/shared/geospatial-map/geospatial-map.component.spec.ts +++ b/src/app/shared/geospatial-map/geospatial-map.component.spec.ts @@ -13,7 +13,9 @@ import { } from '@ngx-translate/core'; import { of } from 'rxjs'; +import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service'; import { getMockTranslateService } from '../mocks/translate.service.mock'; +import { SearchConfigurationServiceStub } from '../testing/search-configuration-service.stub'; import { GeospatialMapComponent } from './geospatial-map.component'; let elRef: ElementRef; @@ -25,7 +27,10 @@ describe('GeospatialMapComponent', () => { beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [GeospatialMapComponent, TranslateModule.forRoot()], - providers: [{ provide: TranslateService, useValue: getMockTranslateService() }], + providers: [ + { provide: TranslateService, useValue: getMockTranslateService() }, + { provide: SearchConfigurationService, useValue: new SearchConfigurationServiceStub() }, + ], schemas: [CUSTOM_ELEMENTS_SCHEMA], }) .compileComponents(); diff --git a/src/app/shared/geospatial-map/geospatial-map.component.ts b/src/app/shared/geospatial-map/geospatial-map.component.ts index c44aa71c727..29afd577493 100644 --- a/src/app/shared/geospatial-map/geospatial-map.component.ts +++ b/src/app/shared/geospatial-map/geospatial-map.component.ts @@ -18,6 +18,7 @@ import { } from 'rxjs'; import { environment } from '../../../environments/environment'; +import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service'; import { hasValue, isEmpty, @@ -100,7 +101,8 @@ export class GeospatialMapComponent implements AfterViewInit, OnInit, OnDestroy constructor(private elRef: ElementRef, @Inject(PLATFORM_ID) private platformId: string, private router: Router, - private translateService: TranslateService) { + private translateService: TranslateService, + private searchConfigurationService: SearchConfigurationService) { } ngOnInit() { @@ -282,8 +284,12 @@ export class GeospatialMapComponent implements AfterViewInit, OnInit, OnDestroy direction: 'top', }).on('click', () => { // On click, make a filtered search using the point filter ('f.point' by default) - this.router.navigate([point.url], - { queryParams: { 'spc.page': 1, [filter]: point.value + ',equals', 'scope': this.currentScope } }); + void this.router.navigate([point.url], + { queryParams: { + [this.searchConfigurationService.getCurrentPageParam()]: 1, + [this.searchConfigurationService.getCurrentSearchInstanceFilterParam(filter)]: point.value + ',equals', + [this.searchConfigurationService.getCurrentSearchInstanceParam('scope')]: this.currentScope, + } }); }); markers.addLayer(marker); } diff --git a/src/app/shared/object-collection/object-collection.component.spec.ts b/src/app/shared/object-collection/object-collection.component.spec.ts index 433fecc2427..f2ecbf807db 100644 --- a/src/app/shared/object-collection/object-collection.component.spec.ts +++ b/src/app/shared/object-collection/object-collection.component.spec.ts @@ -13,11 +13,13 @@ import { provideMockStore } from '@ngrx/store/testing'; import { of } from 'rxjs'; import { ViewMode } from '../../core/shared/view-mode.model'; +import { SEARCH_CONFIG_SERVICE } from '../../my-dspace-page/my-dspace-configuration.service'; import { getMockThemeService } from '../mocks/theme-service.mock'; import { ObjectDetailComponent } from '../object-detail/object-detail.component'; import { ObjectGridComponent } from '../object-grid/object-grid.component'; import { ThemedObjectListComponent } from '../object-list/themed-object-list.component'; import { RouterStub } from '../testing/router.stub'; +import { SearchConfigurationServiceStub } from '../testing/search-configuration-service.stub'; import { ThemeService } from '../theme-support/theme.service'; import { ObjectCollectionComponent } from './object-collection.component'; @@ -83,4 +85,71 @@ describe('ObjectCollectionComponent', () => { expect(comp).not.toBeNull(); expect(comp.nativeElement.classList).not.toContain('hide-placeholder-text'); }); + + it('should default to list view when no view query param is present', (done) => { + objectCollectionComponent.currentMode$.subscribe((mode) => { + expect(mode).toBe(ViewMode.ListElement); + done(); + }); + }); +}); + +describe('ObjectCollectionComponent view query param fallback', () => { + let fixture: ComponentFixture; + let objectCollectionComponent: ObjectCollectionComponent; + + function init(queryParams: Record, provideSearchConfig = false) { + TestBed.resetTestingModule(); + const providers: any[] = [ + { provide: ActivatedRoute, useValue: { queryParams: of(queryParams) } }, + { provide: Router, useClass: RouterStub }, + { provide: ThemeService, useValue: getMockThemeService() }, + provideMockStore(), + ]; + if (provideSearchConfig) { + providers.push({ provide: SEARCH_CONFIG_SERVICE, useValue: new SearchConfigurationServiceStub() }); + } + TestBed.configureTestingModule({ + imports: [ObjectCollectionComponent], + providers, + schemas: [NO_ERRORS_SCHEMA], + }) + .overrideComponent(ObjectCollectionComponent, { + remove: { + imports: [ ThemedObjectListComponent, ObjectGridComponent, ObjectDetailComponent], + }, + }); + fixture = TestBed.createComponent(ObjectCollectionComponent); + objectCollectionComponent = fixture.componentInstance; + fixture.detectChanges(); + } + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('should use the unprefixed view query param when SEARCH_CONFIG_SERVICE is not provided', (done) => { + init({ view: ViewMode.GridElement }); + objectCollectionComponent.currentMode$.subscribe((mode) => { + expect(mode).toBe(ViewMode.GridElement); + done(); + }); + }); + + it('should use the prefixed view query param from SearchConfigurationService', (done) => { + init({ 'test-id.view': ViewMode.GridElement }, true); + objectCollectionComponent.currentMode$.subscribe((mode) => { + expect(mode).toBe(ViewMode.GridElement); + done(); + }); + }); + + it('should prefer an explicit viewMode input over the query param', (done) => { + init({ 'test-id.view': ViewMode.GridElement }, true); + objectCollectionComponent.viewMode = ViewMode.DetailedListElement; + objectCollectionComponent.currentMode$.subscribe((mode) => { + expect(mode).toBe(ViewMode.DetailedListElement); + done(); + }); + }); }); diff --git a/src/app/shared/object-collection/object-collection.component.ts b/src/app/shared/object-collection/object-collection.component.ts index 80b3520400d..d223326e3bd 100644 --- a/src/app/shared/object-collection/object-collection.component.ts +++ b/src/app/shared/object-collection/object-collection.component.ts @@ -11,6 +11,7 @@ import { Inject, Input, OnInit, + Optional, Output, PLATFORM_ID, } from '@angular/core'; @@ -36,7 +37,9 @@ import { PaginatedList } from '../../core/data/paginated-list.model'; import { RemoteData } from '../../core/data/remote-data'; import { Context } from '../../core/shared/context.model'; import { PageInfo } from '../../core/shared/page-info.model'; +import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service'; import { ViewMode } from '../../core/shared/view-mode.model'; +import { SEARCH_CONFIG_SERVICE } from '../../my-dspace-page/my-dspace-configuration.service'; import { isEmpty } from '../empty.util'; import { ObjectDetailComponent } from '../object-detail/object-detail.component'; import { ObjectGeospatialMapComponent } from '../object-geospatial-map/object-geospatial-map.component'; @@ -151,7 +154,7 @@ export class ObjectCollectionComponent implements OnInit { @Input() showThumbnails; /** - * The view mode to render. When not provided, this component falls back to the legacy `view` URL parameter. + * The view mode to render. When not provided, this component falls back to the search-instance `view` URL parameter. */ @Input() set viewMode(viewMode: ViewMode) { this.viewMode$.next(viewMode); @@ -236,13 +239,16 @@ export class ObjectCollectionComponent implements OnInit { private route: ActivatedRoute, private router: Router, private elementRef: ElementRef, - @Inject(PLATFORM_ID) private platformId: any) { + @Inject(PLATFORM_ID) private platformId: any, + @Optional() @Inject(SEARCH_CONFIG_SERVICE) private searchConfigService: SearchConfigurationService, + ) { } ngOnInit(): void { + const viewParam = this.searchConfigService?.getCurrentSearchInstanceParam('view') ?? 'view'; this.currentMode$ = observableCombineLatest([this.route.queryParams, this.viewMode$]) .pipe( - map(([params, viewMode]) => viewMode || (isEmpty(params?.view) ? ViewMode.ListElement : params.view)), + map(([params, viewMode]) => viewMode || (isEmpty(params?.[viewParam]) ? ViewMode.ListElement : params[viewParam])), distinctUntilChanged(), ); if (isPlatformBrowser(this.platformId)) { diff --git a/src/app/shared/object-geospatial-map/object-geospatial-map.component.spec.ts b/src/app/shared/object-geospatial-map/object-geospatial-map.component.spec.ts index 6101e0db6ef..9d7a50f7daf 100644 --- a/src/app/shared/object-geospatial-map/object-geospatial-map.component.spec.ts +++ b/src/app/shared/object-geospatial-map/object-geospatial-map.component.spec.ts @@ -17,11 +17,13 @@ import { import { buildPaginatedList } from '../../core/data/paginated-list.model'; import { Item } from '../../core/shared/item.model'; import { PageInfo } from '../../core/shared/page-info.model'; +import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service'; import { GeospatialMapDetail } from '../geospatial-map/models/geospatial-map-detail.model'; import { TranslateLoaderMock } from '../mocks/translate-loader.mock'; import { ItemSearchResult } from '../object-collection/shared/item-search-result.model'; import { PaginationComponent } from '../pagination/pagination.component'; import { createSuccessfulRemoteDataObject$ } from '../remote-data.utils'; +import { SearchConfigurationServiceStub } from '../testing/search-configuration-service.stub'; import { ObjectGeospatialMapComponent } from './object-geospatial-map.component'; describe('ObjectGeospatialMapComponent', () => { @@ -70,7 +72,13 @@ describe('ObjectGeospatialMapComponent', () => { provide: TranslateLoader, }, })], - providers: [TranslateService, TranslateStore, TranslateLoader, TranslateLoaderMock], + providers: [ + TranslateService, + TranslateStore, + TranslateLoader, + TranslateLoaderMock, + { provide: SearchConfigurationService, useValue: new SearchConfigurationServiceStub() }, + ], schemas: [NO_ERRORS_SCHEMA], }).overrideComponent(ObjectGeospatialMapComponent, { remove: { diff --git a/src/app/shared/rss-feed/rss.component.spec.ts b/src/app/shared/rss-feed/rss.component.spec.ts index 7042fd8ff19..38c5c77d04f 100644 --- a/src/app/shared/rss-feed/rss.component.spec.ts +++ b/src/app/shared/rss-feed/rss.component.spec.ts @@ -21,7 +21,7 @@ import { PaginationService } from '../../core/pagination/pagination.service'; import { LinkHeadService } from '../../core/services/link-head.service'; import { Collection } from '../../core/shared/collection.model'; import { ConfigurationProperty } from '../../core/shared/configuration-property.model'; -import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service'; +import { SEARCH_CONFIG_SERVICE } from '../../my-dspace-page/my-dspace-configuration.service'; import { MockActivatedRoute } from '../mocks/active-router.mock'; import { RouterMock } from '../mocks/router.mock'; import { getMockTranslateService } from '../mocks/translate.service.mock'; @@ -95,7 +95,7 @@ describe('RssComponent', () => { { provide: GroupDataService, useValue: groupDataService }, { provide: LinkHeadService, useValue: linkHeadService }, { provide: ConfigurationDataService, useValue: configurationDataService }, - { provide: SearchConfigurationService, useValue: new SearchConfigurationServiceStub() }, + { provide: SEARCH_CONFIG_SERVICE, useValue: new SearchConfigurationServiceStub() }, { provide: PaginationService, useValue: paginationService }, { provide: Router, useValue: new RouterMock() }, { provide: ActivatedRoute, useValue: new MockActivatedRoute }, diff --git a/src/app/shared/rss-feed/rss.component.ts b/src/app/shared/rss-feed/rss.component.ts index 5345ad7ee80..48cb5fd350c 100644 --- a/src/app/shared/rss-feed/rss.component.ts +++ b/src/app/shared/rss-feed/rss.component.ts @@ -2,6 +2,7 @@ import { AsyncPipe } from '@angular/common'; import { ChangeDetectionStrategy, Component, + Inject, Input, OnChanges, OnDestroy, @@ -34,6 +35,7 @@ import { PaginationService } from '../../core/pagination/pagination.service'; import { LinkHeadService } from '../../core/services/link-head.service'; import { getFirstCompletedRemoteData } from '../../core/shared/operators'; import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service'; +import { SEARCH_CONFIG_SERVICE } from '../../my-dspace-page/my-dspace-configuration.service'; import { hasValue, isUndefined, @@ -69,7 +71,7 @@ export class RSSComponent implements OnInit, OnDestroy, OnChanges { constructor(private groupDataService: GroupDataService, private linkHeadService: LinkHeadService, private configurationService: ConfigurationDataService, - private searchConfigurationService: SearchConfigurationService, + @Inject(SEARCH_CONFIG_SERVICE) private searchConfigurationService: SearchConfigurationService, private router: Router, private route: ActivatedRoute, protected paginationService: PaginationService, diff --git a/src/app/shared/search/advanced-search/advanced-search.component.spec.ts b/src/app/shared/search/advanced-search/advanced-search.component.spec.ts index ea3394c4aeb..04b6ebb3144 100644 --- a/src/app/shared/search/advanced-search/advanced-search.component.spec.ts +++ b/src/app/shared/search/advanced-search/advanced-search.component.spec.ts @@ -8,8 +8,8 @@ import { TranslateModule } from '@ngx-translate/core'; import { APP_CONFIG } from '../../../../config/app-config.interface'; import { environment } from '../../../../environments/environment.test'; import { SearchService } from '../../../core/shared/search/search.service'; -import { SearchConfigurationService } from '../../../core/shared/search/search-configuration.service'; import { SearchFilterService } from '../../../core/shared/search/search-filter.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../my-dspace-page/my-dspace-configuration.service'; import { RouterStub } from '../../testing/router.stub'; import { SearchConfigurationServiceStub } from '../../testing/search-configuration-service.stub'; import { SearchFilterServiceStub } from '../../testing/search-filter-service.stub'; @@ -39,7 +39,7 @@ describe('AdvancedSearchComponent', () => { providers: [ { provide: Router, useValue: router }, { provide: SearchService, useValue: searchService }, - { provide: SearchConfigurationService, useValue: searchConfigurationService }, + { provide: SEARCH_CONFIG_SERVICE, useValue: searchConfigurationService }, { provide: SearchFilterService, useValue: searchFilterService }, { provide: APP_CONFIG, useValue: environment }, ], diff --git a/src/app/shared/search/advanced-search/advanced-search.component.ts b/src/app/shared/search/advanced-search/advanced-search.component.ts index d91a8ab9778..9482668ee13 100644 --- a/src/app/shared/search/advanced-search/advanced-search.component.ts +++ b/src/app/shared/search/advanced-search/advanced-search.component.ts @@ -27,6 +27,7 @@ import { SearchService } from '../../../core/shared/search/search.service'; import { SearchConfigurationService } from '../../../core/shared/search/search-configuration.service'; import { SearchFilterService } from '../../../core/shared/search/search-filter.service'; import { FilterConfig } from '../../../core/shared/search/search-filters/search-config.model'; +import { SEARCH_CONFIG_SERVICE } from '../../../my-dspace-page/my-dspace-configuration.service'; import { BtnDisabledDirective } from '../../btn-disabled.directive'; import { hasValue, @@ -98,7 +99,7 @@ export class AdvancedSearchComponent implements OnInit, OnDestroy { constructor( protected router: Router, protected searchService: SearchService, - protected searchConfigurationService: SearchConfigurationService, + @Inject(SEARCH_CONFIG_SERVICE) protected searchConfigurationService: SearchConfigurationService, protected searchFilterService: SearchFilterService, @Inject(APP_CONFIG) protected appConfig: AppConfig, ) { diff --git a/src/app/shared/search/search-labels/search-label-range/search-label-range.component.spec.ts b/src/app/shared/search/search-labels/search-label-range/search-label-range.component.spec.ts index eee1c75850d..dbe9b1cbf29 100644 --- a/src/app/shared/search/search-labels/search-label-range/search-label-range.component.spec.ts +++ b/src/app/shared/search/search-labels/search-label-range/search-label-range.component.spec.ts @@ -12,8 +12,8 @@ import { TranslateModule } from '@ngx-translate/core'; import { PaginationService } from '../../../../core/pagination/pagination.service'; import { SearchService } from '../../../../core/shared/search/search.service'; -import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service'; import { SearchFilterService } from '../../../../core/shared/search/search-filter.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../../my-dspace-page/my-dspace-configuration.service'; import { PaginationComponentOptions } from '../../../pagination/pagination-component-options.model'; import { ActivatedRouteStub } from '../../../testing/active-router.stub'; import { PaginationServiceStub } from '../../../testing/pagination-service.stub'; @@ -72,7 +72,7 @@ describe('SearchLabelRangeComponent', () => { ], providers: [ { provide: PaginationService, useValue: paginationService }, - { provide: SearchConfigurationService, useValue: searchConfigurationService }, + { provide: SEARCH_CONFIG_SERVICE, useValue: searchConfigurationService }, { provide: SearchService, useValue: new SearchServiceStub(searchLink) }, { provide: SearchFilterService, useValue: searchFilterService }, { provide: ActivatedRoute, useValue: route }, diff --git a/src/app/shared/search/search-labels/search-label-range/search-label-range.component.ts b/src/app/shared/search/search-labels/search-label-range/search-label-range.component.ts index cef2041d077..6b092aeeeda 100644 --- a/src/app/shared/search/search-labels/search-label-range/search-label-range.component.ts +++ b/src/app/shared/search/search-labels/search-label-range/search-label-range.component.ts @@ -1,6 +1,7 @@ import { AsyncPipe } from '@angular/common'; import { Component, + Inject, Input, OnInit, } from '@angular/core'; @@ -16,6 +17,7 @@ import { PaginationService } from '../../../../core/pagination/pagination.servic import { SearchService } from '../../../../core/shared/search/search.service'; import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service'; import { SearchFilterService } from '../../../../core/shared/search/search-filter.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../../my-dspace-page/my-dspace-configuration.service'; import { currentPath } from '../../../utils/route.utils'; import { AppliedFilter } from '../../models/applied-filter.model'; @@ -51,7 +53,7 @@ export class SearchLabelRangeComponent implements OnInit { constructor( protected paginationService: PaginationService, protected router: Router, - protected searchConfigurationService: SearchConfigurationService, + @Inject(SEARCH_CONFIG_SERVICE) protected searchConfigurationService: SearchConfigurationService, protected searchService: SearchService, protected searchFilterService: SearchFilterService, ) { diff --git a/src/app/shared/search/search-results/search-results.component.spec.ts b/src/app/shared/search/search-results/search-results.component.spec.ts index 33b8432b749..e1b4e3dc698 100644 --- a/src/app/shared/search/search-results/search-results.component.spec.ts +++ b/src/app/shared/search/search-results/search-results.component.spec.ts @@ -14,7 +14,7 @@ import { TranslateModule } from '@ngx-translate/core'; import { Community } from '../../../core/shared/community.model'; import { SearchService } from '../../../core/shared/search/search.service'; -import { SearchConfigurationService } from '../../../core/shared/search/search-configuration.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../my-dspace-page/my-dspace-configuration.service'; import { ErrorComponent } from '../../error/error.component'; import { getMockThemeService } from '../../mocks/theme-service.mock'; import { ObjectCollectionComponent } from '../../object-collection/object-collection.component'; @@ -41,7 +41,7 @@ describe('SearchResultsComponent', () => { { provide: ThemeService, useValue: getMockThemeService() }, { provide: SearchService, useValue: new SearchServiceStub() }, { - provide: SearchConfigurationService, + provide: SEARCH_CONFIG_SERVICE, useValue: new SearchConfigurationServiceStub(), }, ], @@ -115,7 +115,7 @@ describe('SearchResultsComponent', () => { const routerLinkQuery = linkDes.map((de) => de.injector.get(QueryParamsDirectiveStub)); expect(routerLinkQuery.length).toBe(1, 'should have 1 router link with query params'); - expect(routerLinkQuery[0].queryParams.query).toBe('"foobar"', 'query params should be "foobar"'); + expect(routerLinkQuery[0].queryParams['test-id.query']).toBe('"foobar"', 'query params should be "foobar"'); }); it('should display link with new search where query is quoted if search result is empty', () => { @@ -130,7 +130,7 @@ describe('SearchResultsComponent', () => { const routerLinkQuery = linkDes.map((de) => de.injector.get(QueryParamsDirectiveStub)); expect(routerLinkQuery.length).toBe(1, 'should have 1 router link with query params'); - expect(routerLinkQuery[0].queryParams.query).toBe('"foobar"', 'query params should be "foobar"'); + expect(routerLinkQuery[0].queryParams['test-id.query']).toBe('"foobar"', 'query params should be "foobar"'); }); it('should add quotes around the given string', () => { diff --git a/src/app/shared/search/search-results/search-results.component.ts b/src/app/shared/search/search-results/search-results.component.ts index 08dda1270f8..91ffd07e4b2 100644 --- a/src/app/shared/search/search-results/search-results.component.ts +++ b/src/app/shared/search/search-results/search-results.component.ts @@ -2,6 +2,7 @@ import { AsyncPipe } from '@angular/common'; import { Component, EventEmitter, + Inject, Input, Output, } from '@angular/core'; @@ -24,6 +25,7 @@ import { DSpaceObject } from '../../../core/shared/dspace-object.model'; import { SearchService } from '../../../core/shared/search/search.service'; import { SearchConfigurationService } from '../../../core/shared/search/search-configuration.service'; import { ViewMode } from '../../../core/shared/view-mode.model'; +import { SEARCH_CONFIG_SERVICE } from '../../../my-dspace-page/my-dspace-configuration.service'; import { fadeIn, fadeInOut, @@ -156,7 +158,7 @@ export class SearchResultsComponent { @Output() selectObject: EventEmitter = new EventEmitter(); constructor( - protected searchConfigService: SearchConfigurationService, + @Inject(SEARCH_CONFIG_SERVICE) protected searchConfigService: SearchConfigurationService, protected searchService: SearchService, ) { this.activeFilters$ = this.searchConfigService.getCurrentFilters(); @@ -192,13 +194,8 @@ export class SearchResultsComponent { } getExactMatchQueryParams(): Params { - if (hasNoValue(this.searchConfig?.pagination?.id)) { - return { - query: this.surroundStringWithQuotes(this.searchConfig?.query), - }; - } return { - [`${this.searchConfig?.pagination?.id}.query`]: this.surroundStringWithQuotes(this.searchConfig?.query), + [this.searchConfigService.getCurrentSearchInstanceParam('query')]: this.surroundStringWithQuotes(this.searchConfig?.query), }; } } diff --git a/src/app/shared/search/search-sidebar/search-sidebar.component.spec.ts b/src/app/shared/search/search-sidebar/search-sidebar.component.spec.ts index b9c61629fcf..5f953b29675 100644 --- a/src/app/shared/search/search-sidebar/search-sidebar.component.spec.ts +++ b/src/app/shared/search/search-sidebar/search-sidebar.component.spec.ts @@ -13,7 +13,7 @@ import { TranslateModule } from '@ngx-translate/core'; import { APP_CONFIG } from '../../../../config/app-config.interface'; import { environment } from '../../../../environments/environment.test'; -import { SearchConfigurationService } from '../../../core/shared/search/search-configuration.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../my-dspace-page/my-dspace-configuration.service'; import { SearchConfigurationServiceStub } from '../../testing/search-configuration-service.stub'; import { AdvancedSearchComponent } from '../advanced-search/advanced-search.component'; import { ThemedSearchFiltersComponent } from '../search-filters/themed-search-filters.component'; @@ -36,7 +36,7 @@ describe('SearchSidebarComponent', () => { SearchSidebarComponent, ], providers: [ - { provide: SearchConfigurationService, useValue: searchConfigurationService }, + { provide: SEARCH_CONFIG_SERVICE, useValue: searchConfigurationService }, ], schemas: [CUSTOM_ELEMENTS_SCHEMA], }).overrideProvider(APP_CONFIG, { diff --git a/src/app/shared/search/search-sidebar/search-sidebar.component.ts b/src/app/shared/search/search-sidebar/search-sidebar.component.ts index 1f7916f037b..55d0554e496 100644 --- a/src/app/shared/search/search-sidebar/search-sidebar.component.ts +++ b/src/app/shared/search/search-sidebar/search-sidebar.component.ts @@ -23,6 +23,7 @@ import { RemoteData } from '../../../core/data/remote-data'; import { SearchConfigurationService } from '../../../core/shared/search/search-configuration.service'; import { FilterConfig } from '../../../core/shared/search/search-filters/search-config.model'; import { ViewMode } from '../../../core/shared/view-mode.model'; +import { SEARCH_CONFIG_SERVICE } from '../../../my-dspace-page/my-dspace-configuration.service'; import { ViewModeSwitchComponent } from '../../view-mode-switch/view-mode-switch.component'; import { AdvancedSearchComponent } from '../advanced-search/advanced-search.component'; import { PaginatedSearchOptions } from '../models/paginated-search-options.model'; @@ -137,7 +138,7 @@ export class SearchSidebarComponent implements OnInit { constructor( @Inject(APP_CONFIG) protected appConfig: AppConfig, - protected searchConfigurationService: SearchConfigurationService, + @Inject(SEARCH_CONFIG_SERVICE) protected searchConfigurationService: SearchConfigurationService, ) { } diff --git a/src/app/shared/theme-support/theme.service.spec.ts b/src/app/shared/theme-support/theme.service.spec.ts index 35e26e9ec34..c5fcdbb5cba 100644 --- a/src/app/shared/theme-support/theme.service.spec.ts +++ b/src/app/shared/theme-support/theme.service.spec.ts @@ -21,6 +21,7 @@ import { COMMUNITY } from '../../core/shared/community.resource-type'; import { DSpaceObject } from '../../core/shared/dspace-object.model'; import { Item } from '../../core/shared/item.model'; import { ITEM } from '../../core/shared/item.resource-type'; +import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service'; import { RouterMock } from '../mocks/router.mock'; import { NoOpAction } from '../ngrx/no-op.action'; import { @@ -29,6 +30,7 @@ import { createSuccessfulRemoteDataObject$, } from '../remote-data.utils'; import { ConfigurationDataServiceStub } from '../testing/configuration-data.service.stub'; +import { SearchConfigurationServiceStub } from '../testing/search-configuration-service.stub'; import { SetThemeAction } from './theme.actions'; import { Theme } from './theme.model'; import { ThemeService } from './theme.service'; @@ -95,6 +97,8 @@ describe('ThemeService', () => { const mockDsoService = { findById: () => createSuccessfulRemoteDataObject$(mockCommunity), }; + const searchConfigService = new SearchConfigurationServiceStub(); + searchConfigService.searchInstanceId = 'spc'; TestBed.configureTestingModule({ imports: [ CommonModule, @@ -107,6 +111,7 @@ describe('ThemeService', () => { { provide: DSpaceObjectDataService, useValue: mockDsoService }, { provide: Router, useValue: new RouterMock() }, { provide: ConfigurationDataService, useValue: configurationService }, + { provide: SearchConfigurationService, useValue: searchConfigService }, ], }); @@ -266,6 +271,48 @@ describe('ThemeService', () => { }); }); }); + + describe('when a prefixed scope is present in the snapshot\'s parameters', () => { + let snapshot; + + beforeEach(() => { + setupServiceWithActions( + hot('--a-', { + a: { + type: ROUTER_NAVIGATED, + payload: { routerState: { url } }, + }, + }), + ); + spyOnPrivateMethods(); + snapshot = Object.assign({ + queryParams: { + 'spc.scope': mockCommunity.uuid, + }, + }); + }); + + it('should match the theme to the dso found through the prefixed scope', (done) => { + themeService.updateThemeOnRouteChange$(url, snapshot).subscribe(() => { + expect((themeService as any).matchThemeToDSOs).toHaveBeenCalled(); + done(); + }); + }); + + it('should set the theme it receives from the dso found through the prefixed scope', (done) => { + themeService.updateThemeOnRouteChange$(url, snapshot).subscribe(() => { + expect((themeService as any).store.dispatch).toHaveBeenCalledWith(new SetThemeAction('custom') as any); + done(); + }); + }); + + it('should return true', (done) => { + themeService.updateThemeOnRouteChange$(url, snapshot).subscribe((result) => { + expect(result).toEqual(true); + done(); + }); + }); + }); }); describe('private functions', () => { @@ -408,6 +455,8 @@ describe('ThemeService', () => { findById: () => createSuccessfulRemoteDataObject$(mockCommunity), }; configurationService = new ConfigurationDataServiceStub(); + const searchConfigService = new SearchConfigurationServiceStub(); + searchConfigService.searchInstanceId = 'spc'; TestBed.configureTestingModule({ imports: [ @@ -420,6 +469,7 @@ describe('ThemeService', () => { { provide: DSpaceObjectDataService, useValue: mockDsoService }, { provide: Router, useValue: new RouterMock() }, { provide: ConfigurationDataService, useValue: configurationService }, + { provide: SearchConfigurationService, useValue: searchConfigService }, ], }); diff --git a/src/app/shared/theme-support/theme.service.ts b/src/app/shared/theme-support/theme.service.ts index bdb1641bb73..9749221fcdc 100644 --- a/src/app/shared/theme-support/theme.service.ts +++ b/src/app/shared/theme-support/theme.service.ts @@ -51,6 +51,7 @@ import { getFirstSucceededRemoteData, getRemoteDataPayload, } from '../../core/shared/operators'; +import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service'; import { hasNoValue, hasValue, @@ -105,6 +106,7 @@ export class ThemeService { @Inject(GET_THEME_CONFIG_FOR_FACTORY) private gtcf: (str) => ThemeConfig, private router: Router, @Inject(DOCUMENT) private document: any, + private searchConfigurationService: SearchConfigurationService, @Optional() private hashedFileMapping: HashedFileMapping, ) { // Create objects from the theme configs in the environment file @@ -364,8 +366,9 @@ export class ThemeService { ); } } - if (hasValue(activatedRouteSnapshot.queryParams) && hasValue(activatedRouteSnapshot.queryParams.scope)) { - const dsoFromScope$: Observable> = this.dSpaceObjectDataService.findById(activatedRouteSnapshot.queryParams.scope); + const scope = this.getScopeFromSnapshot(activatedRouteSnapshot); + if (hasValue(scope)) { + const dsoFromScope$: Observable> = this.dSpaceObjectDataService.findById(scope); // Start with the resolved dso and go recursively through its parents until you reach the top-level community return dsoFromScope$.pipe( getFirstSucceededRemoteData(), @@ -409,6 +412,20 @@ export class ThemeService { ); } + /** + * Resolve the search scope from the route snapshot, preferring the search-instance prefixed + * parameter and falling back to the legacy unprefixed `scope` query parameter. + * @param activatedRouteSnapshot + * @private + */ + private getScopeFromSnapshot(activatedRouteSnapshot: ActivatedRouteSnapshot): string { + if (hasNoValue(activatedRouteSnapshot.queryParams)) { + return undefined; + } + const scopeParam = this.searchConfigurationService.getCurrentSearchInstanceParam('scope'); + return activatedRouteSnapshot.queryParams[scopeParam] || activatedRouteSnapshot.queryParams.scope; + } + /** * Find a DSpaceObject in one of the provided route snapshots their data * Recursively looks for the dso in the routes their child routes until it reaches a dead end or finds one From 980b23c91f5667f30a8706726fc4ea30604be480 Mon Sep 17 00:00:00 2001 From: Ali Jaber Date: Sat, 22 Aug 2026 10:23:13 -0400 Subject: [PATCH 6/9] 143851: centralize view and snapshot search params --- .../search-configuration.service.spec.ts | 19 ++++++++ .../search/search-configuration.service.ts | 20 +++++++- .../object-collection.component.spec.ts | 48 +++++-------------- .../object-collection.component.ts | 38 +-------------- .../search-results.component.html | 1 - .../search-results.component.ts | 6 --- .../themed-search-results.component.ts | 5 +- .../search-configuration-service.stub.ts | 9 ++++ .../theme-support/theme.service.spec.ts | 9 +++- src/app/shared/theme-support/theme.service.ts | 16 +------ 10 files changed, 70 insertions(+), 101 deletions(-) diff --git a/src/app/core/shared/search/search-configuration.service.spec.ts b/src/app/core/shared/search/search-configuration.service.spec.ts index 817dab018db..890de831184 100644 --- a/src/app/core/shared/search/search-configuration.service.spec.ts +++ b/src/app/core/shared/search/search-configuration.service.spec.ts @@ -327,6 +327,25 @@ describe('SearchConfigurationService', () => { }); }); + describe('getSearchParamFromParams', () => { + it('should prefer the search-instance-prefixed value', () => { + const params: Params = { + [`${defaults.pagination.id}.scope`]: 'prefixed scope', + scope: 'legacy scope', + }; + + expect(service.getSearchParamFromParams(params, 'scope')).toBe('prefixed scope'); + }); + + it('should fall back to the legacy unprefixed value', () => { + expect(service.getSearchParamFromParams({ scope: 'legacy scope' }, 'scope')).toBe('legacy scope'); + }); + + it('should return undefined when the parameter is absent', () => { + expect(service.getSearchParamFromParams({}, 'scope')).toBeUndefined(); + }); + }); + describe('with legacy search parameter fallback disabled', () => { beforeEach(() => { service.useLegacySearchParamFallback = false; diff --git a/src/app/core/shared/search/search-configuration.service.ts b/src/app/core/shared/search/search-configuration.service.ts index 0581fe98e04..332b9900d74 100644 --- a/src/app/core/shared/search/search-configuration.service.ts +++ b/src/app/core/shared/search/search-configuration.service.ts @@ -310,9 +310,9 @@ export class SearchConfigurationService implements OnDestroy { /** * @returns {Observable} Emits the current view mode */ - getCurrentViewMode(defaultViewMode: ViewMode, searchInstanceId = this.searchInstanceId) { + getCurrentViewMode(defaultViewMode: ViewMode, searchInstanceId = this.searchInstanceId): Observable { return this.getCurrentSearchInstanceQueryParam(searchInstanceId, 'view').pipe(map((viewMode) => { - return viewMode || defaultViewMode; + return (viewMode as ViewMode) || defaultViewMode; })); } @@ -384,6 +384,22 @@ export class SearchConfigurationService implements OnDestroy { return this.getSearchInstanceParam(this.searchInstanceId, parameterName); } + /** + * Resolve a search parameter from a Params object, preferring the search-instance-prefixed + * value and falling back to the legacy unprefixed value. + * + * @param params The parameters to read from + * @param parameterName The search parameter name + * @param searchInstanceId The search instance identifier + */ + getSearchParamFromParams(params: Params, parameterName: string, searchInstanceId = this.searchInstanceId): string { + if (hasNoValue(params)) { + return undefined; + } + const instanceValue = params[this.getSearchInstanceParam(searchInstanceId, parameterName)]; + return hasValue(instanceValue) ? instanceValue : params[parameterName]; + } + getSearchInstanceFilterParam(filterName: string, searchInstanceId = this.searchInstanceId): string { const filterParamName = filterName.startsWith('f.') ? filterName : `f.${filterName}`; return this.getSearchInstanceParam(searchInstanceId, filterParamName); diff --git a/src/app/shared/object-collection/object-collection.component.spec.ts b/src/app/shared/object-collection/object-collection.component.spec.ts index f2ecbf807db..9b0e9f1ceab 100644 --- a/src/app/shared/object-collection/object-collection.component.spec.ts +++ b/src/app/shared/object-collection/object-collection.component.spec.ts @@ -5,10 +5,6 @@ import { waitForAsync, } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; -import { - ActivatedRoute, - Router, -} from '@angular/router'; import { provideMockStore } from '@ngrx/store/testing'; import { of } from 'rxjs'; @@ -18,7 +14,6 @@ import { getMockThemeService } from '../mocks/theme-service.mock'; import { ObjectDetailComponent } from '../object-detail/object-detail.component'; import { ObjectGridComponent } from '../object-grid/object-grid.component'; import { ThemedObjectListComponent } from '../object-list/themed-object-list.component'; -import { RouterStub } from '../testing/router.stub'; import { SearchConfigurationServiceStub } from '../testing/search-configuration-service.stub'; import { ThemeService } from '../theme-support/theme.service'; import { ObjectCollectionComponent } from './object-collection.component'; @@ -27,20 +22,10 @@ describe('ObjectCollectionComponent', () => { let fixture: ComponentFixture; let objectCollectionComponent: ObjectCollectionComponent; - const queryParam = 'test query'; - const scopeParam = '7669c72a-3f2a-451f-a3b9-9210e7a4c02f'; - const activatedRouteStub = { - queryParams: of({ - query: queryParam, - scope: scopeParam, - }), - }; beforeEach(waitForAsync(async () => { await TestBed.configureTestingModule({ imports: [ObjectCollectionComponent], providers: [ - { provide: ActivatedRoute, useValue: activatedRouteStub }, - { provide: Router, useClass: RouterStub }, { provide: ThemeService, useValue: getMockThemeService() }, provideMockStore(), ], @@ -94,20 +79,21 @@ describe('ObjectCollectionComponent', () => { }); }); -describe('ObjectCollectionComponent view query param fallback', () => { +describe('ObjectCollectionComponent view mode', () => { let fixture: ComponentFixture; let objectCollectionComponent: ObjectCollectionComponent; + let searchConfigService: SearchConfigurationServiceStub; - function init(queryParams: Record, provideSearchConfig = false) { + function init(viewMode?: ViewMode) { TestBed.resetTestingModule(); const providers: any[] = [ - { provide: ActivatedRoute, useValue: { queryParams: of(queryParams) } }, - { provide: Router, useClass: RouterStub }, { provide: ThemeService, useValue: getMockThemeService() }, provideMockStore(), ]; - if (provideSearchConfig) { - providers.push({ provide: SEARCH_CONFIG_SERVICE, useValue: new SearchConfigurationServiceStub() }); + if (viewMode) { + searchConfigService = new SearchConfigurationServiceStub(); + spyOn(searchConfigService, 'getCurrentViewMode').and.returnValue(of(viewMode)); + providers.push({ provide: SEARCH_CONFIG_SERVICE, useValue: searchConfigService }); } TestBed.configureTestingModule({ imports: [ObjectCollectionComponent], @@ -128,27 +114,19 @@ describe('ObjectCollectionComponent view query param fallback', () => { TestBed.resetTestingModule(); }); - it('should use the unprefixed view query param when SEARCH_CONFIG_SERVICE is not provided', (done) => { - init({ view: ViewMode.GridElement }); + it('should default to list view when SEARCH_CONFIG_SERVICE is not provided', (done) => { + init(); objectCollectionComponent.currentMode$.subscribe((mode) => { - expect(mode).toBe(ViewMode.GridElement); + expect(mode).toBe(ViewMode.ListElement); done(); }); }); - it('should use the prefixed view query param from SearchConfigurationService', (done) => { - init({ 'test-id.view': ViewMode.GridElement }, true); + it('should get the current view mode from SearchConfigurationService', (done) => { + init(ViewMode.GridElement); objectCollectionComponent.currentMode$.subscribe((mode) => { expect(mode).toBe(ViewMode.GridElement); - done(); - }); - }); - - it('should prefer an explicit viewMode input over the query param', (done) => { - init({ 'test-id.view': ViewMode.GridElement }, true); - objectCollectionComponent.viewMode = ViewMode.DetailedListElement; - objectCollectionComponent.currentMode$.subscribe((mode) => { - expect(mode).toBe(ViewMode.DetailedListElement); + expect(searchConfigService.getCurrentViewMode).toHaveBeenCalledWith(ViewMode.ListElement); done(); }); }); diff --git a/src/app/shared/object-collection/object-collection.component.ts b/src/app/shared/object-collection/object-collection.component.ts index d223326e3bd..2a379bb7d52 100644 --- a/src/app/shared/object-collection/object-collection.component.ts +++ b/src/app/shared/object-collection/object-collection.component.ts @@ -4,7 +4,6 @@ import { NgClass, } from '@angular/common'; import { - ChangeDetectorRef, Component, ElementRef, EventEmitter, @@ -16,18 +15,9 @@ import { PLATFORM_ID, } from '@angular/core'; import { - ActivatedRoute, - Router, -} from '@angular/router'; -import { - BehaviorSubject, - combineLatest as observableCombineLatest, Observable, + of, } from 'rxjs'; -import { - distinctUntilChanged, - map, -} from 'rxjs/operators'; import { SortDirection, @@ -40,7 +30,6 @@ import { PageInfo } from '../../core/shared/page-info.model'; import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service'; import { ViewMode } from '../../core/shared/view-mode.model'; import { SEARCH_CONFIG_SERVICE } from '../../my-dspace-page/my-dspace-configuration.service'; -import { isEmpty } from '../empty.util'; import { ObjectDetailComponent } from '../object-detail/object-detail.component'; import { ObjectGeospatialMapComponent } from '../object-geospatial-map/object-geospatial-map.component'; import { ObjectGridComponent } from '../object-grid/object-grid.component'; @@ -153,13 +142,6 @@ export class ObjectCollectionComponent implements OnInit { */ @Input() showThumbnails; - /** - * The view mode to render. When not provided, this component falls back to the search-instance `view` URL parameter. - */ - @Input() set viewMode(viewMode: ViewMode) { - this.viewMode$.next(viewMode); - } - /** * the page info of the list */ @@ -209,8 +191,6 @@ export class ObjectCollectionComponent implements OnInit { */ currentMode$: Observable; - private viewMode$: BehaviorSubject = new BehaviorSubject(undefined); - /** * The available view modes */ @@ -225,19 +205,10 @@ export class ObjectCollectionComponent implements OnInit { /** - * @param cdRef - * ChangeDetectorRef service provided by Angular. - * @param route - * Route is a singleton service provided by Angular. - * @param router - * Router is a singleton service provided by Angular. * @param elementRef * Used only to read DOM for the element width */ constructor( - private cdRef: ChangeDetectorRef, - private route: ActivatedRoute, - private router: Router, private elementRef: ElementRef, @Inject(PLATFORM_ID) private platformId: any, @Optional() @Inject(SEARCH_CONFIG_SERVICE) private searchConfigService: SearchConfigurationService, @@ -245,12 +216,7 @@ export class ObjectCollectionComponent implements OnInit { } ngOnInit(): void { - const viewParam = this.searchConfigService?.getCurrentSearchInstanceParam('view') ?? 'view'; - this.currentMode$ = observableCombineLatest([this.route.queryParams, this.viewMode$]) - .pipe( - map(([params, viewMode]) => viewMode || (isEmpty(params?.[viewParam]) ? ViewMode.ListElement : params[viewParam])), - distinctUntilChanged(), - ); + this.currentMode$ = this.searchConfigService?.getCurrentViewMode(ViewMode.ListElement) ?? of(ViewMode.ListElement); if (isPlatformBrowser(this.platformId)) { const width = this.elementRef.nativeElement.offsetWidth; this.placeholderFontClass = setPlaceHolderAttributes(width); diff --git a/src/app/shared/search/search-results/search-results.component.html b/src/app/shared/search/search-results/search-results.component.html index 865b77759f8..08874663341 100644 --- a/src/app/shared/search/search-results/search-results.component.html +++ b/src/app/shared/search/search-results/search-results.component.html @@ -30,7 +30,6 @@

{{ (configuration ? configuration + '.search.results.head' : 'search.results [selectionConfig]="selectionConfig" [linkType]="linkType" [context]="context" - [viewMode]="searchConfig?.view" [hidePaginationDetail]="hidePaginationDetail" [showThumbnails]="showThumbnails" (contentChange)="contentChange.emit($event)" diff --git a/src/app/shared/search/search-results/search-results.component.ts b/src/app/shared/search/search-results/search-results.component.ts index 91ffd07e4b2..a67ccc47155 100644 --- a/src/app/shared/search/search-results/search-results.component.ts +++ b/src/app/shared/search/search-results/search-results.component.ts @@ -24,7 +24,6 @@ import { Context } from '../../../core/shared/context.model'; import { DSpaceObject } from '../../../core/shared/dspace-object.model'; import { SearchService } from '../../../core/shared/search/search.service'; import { SearchConfigurationService } from '../../../core/shared/search/search-configuration.service'; -import { ViewMode } from '../../../core/shared/view-mode.model'; import { SEARCH_CONFIG_SERVICE } from '../../../my-dspace-page/my-dspace-configuration.service'; import { fadeIn, @@ -115,11 +114,6 @@ export class SearchResultsComponent { */ @Input() sortConfig: SortOptions; - /** - * The current view-mode of the list - */ - @Input() viewMode: ViewMode; - /** * An optional configuration to filter the result on one type */ diff --git a/src/app/shared/search/search-results/themed-search-results.component.ts b/src/app/shared/search/search-results/themed-search-results.component.ts index d8106ef7724..d32725d81ad 100644 --- a/src/app/shared/search/search-results/themed-search-results.component.ts +++ b/src/app/shared/search/search-results/themed-search-results.component.ts @@ -10,7 +10,6 @@ import { PaginatedList } from '../../../core/data/paginated-list.model'; import { RemoteData } from '../../../core/data/remote-data'; import { Context } from '../../../core/shared/context.model'; import { DSpaceObject } from '../../../core/shared/dspace-object.model'; -import { ViewMode } from '../../../core/shared/view-mode.model'; import { CollectionElementLinkType } from '../../object-collection/collection-element-link.type'; import { ListableObject } from '../../object-collection/shared/listable-object.model'; import { ThemedComponent } from '../../theme-support/themed.component'; @@ -30,7 +29,7 @@ import { }) export class ThemedSearchResultsComponent extends ThemedComponent { - protected inAndOutputNames: (keyof SearchResultsComponent & keyof this)[] = ['linkType', 'searchResults', 'searchConfig', 'showCsvExport', 'showThumbnails', 'sortConfig', 'viewMode', 'configuration', 'disableHeader', 'selectable', 'context', 'hidePaginationDetail', 'selectionConfig', 'contentChange', 'deselectObject', 'selectObject']; + protected inAndOutputNames: (keyof SearchResultsComponent & keyof this)[] = ['linkType', 'searchResults', 'searchConfig', 'showCsvExport', 'showThumbnails', 'sortConfig', 'configuration', 'disableHeader', 'selectable', 'context', 'hidePaginationDetail', 'selectionConfig', 'contentChange', 'deselectObject', 'selectObject']; @Input() linkType: CollectionElementLinkType; @@ -44,8 +43,6 @@ export class ThemedSearchResultsComponent extends ThemedComponent { return of([]); } diff --git a/src/app/shared/theme-support/theme.service.spec.ts b/src/app/shared/theme-support/theme.service.spec.ts index c5fcdbb5cba..e7c8570976f 100644 --- a/src/app/shared/theme-support/theme.service.spec.ts +++ b/src/app/shared/theme-support/theme.service.spec.ts @@ -60,6 +60,7 @@ describe('ThemeService', () => { let themeService: ThemeService; let linkService: LinkService; let configurationService: ConfigurationDataServiceStub; + let searchConfigService: SearchConfigurationServiceStub; let initialState; let ancestorDSOs: DSpaceObject[]; @@ -97,7 +98,7 @@ describe('ThemeService', () => { const mockDsoService = { findById: () => createSuccessfulRemoteDataObject$(mockCommunity), }; - const searchConfigService = new SearchConfigurationServiceStub(); + searchConfigService = new SearchConfigurationServiceStub(); searchConfigService.searchInstanceId = 'spc'; TestBed.configureTestingModule({ imports: [ @@ -243,6 +244,7 @@ describe('ThemeService', () => { }), ); spyOnPrivateMethods(); + spyOn(searchConfigService, 'getSearchParamFromParams').and.callThrough(); snapshot = Object.assign({ queryParams: { scope: mockCommunity.uuid, @@ -253,6 +255,7 @@ describe('ThemeService', () => { it('should match the theme to the dso found through the scope', (done) => { themeService.updateThemeOnRouteChange$(url, snapshot).subscribe(() => { expect((themeService as any).matchThemeToDSOs).toHaveBeenCalled(); + expect(searchConfigService.getSearchParamFromParams).toHaveBeenCalledWith(snapshot.queryParams, 'scope'); done(); }); }); @@ -285,6 +288,7 @@ describe('ThemeService', () => { }), ); spyOnPrivateMethods(); + spyOn(searchConfigService, 'getSearchParamFromParams').and.callThrough(); snapshot = Object.assign({ queryParams: { 'spc.scope': mockCommunity.uuid, @@ -295,6 +299,7 @@ describe('ThemeService', () => { it('should match the theme to the dso found through the prefixed scope', (done) => { themeService.updateThemeOnRouteChange$(url, snapshot).subscribe(() => { expect((themeService as any).matchThemeToDSOs).toHaveBeenCalled(); + expect(searchConfigService.getSearchParamFromParams).toHaveBeenCalledWith(snapshot.queryParams, 'scope'); done(); }); }); @@ -455,7 +460,7 @@ describe('ThemeService', () => { findById: () => createSuccessfulRemoteDataObject$(mockCommunity), }; configurationService = new ConfigurationDataServiceStub(); - const searchConfigService = new SearchConfigurationServiceStub(); + searchConfigService = new SearchConfigurationServiceStub(); searchConfigService.searchInstanceId = 'spc'; TestBed.configureTestingModule({ diff --git a/src/app/shared/theme-support/theme.service.ts b/src/app/shared/theme-support/theme.service.ts index 9749221fcdc..ac8eac53b71 100644 --- a/src/app/shared/theme-support/theme.service.ts +++ b/src/app/shared/theme-support/theme.service.ts @@ -366,7 +366,7 @@ export class ThemeService { ); } } - const scope = this.getScopeFromSnapshot(activatedRouteSnapshot); + const scope = this.searchConfigurationService.getSearchParamFromParams(activatedRouteSnapshot.queryParams, 'scope'); if (hasValue(scope)) { const dsoFromScope$: Observable> = this.dSpaceObjectDataService.findById(scope); // Start with the resolved dso and go recursively through its parents until you reach the top-level community @@ -412,20 +412,6 @@ export class ThemeService { ); } - /** - * Resolve the search scope from the route snapshot, preferring the search-instance prefixed - * parameter and falling back to the legacy unprefixed `scope` query parameter. - * @param activatedRouteSnapshot - * @private - */ - private getScopeFromSnapshot(activatedRouteSnapshot: ActivatedRouteSnapshot): string { - if (hasNoValue(activatedRouteSnapshot.queryParams)) { - return undefined; - } - const scopeParam = this.searchConfigurationService.getCurrentSearchInstanceParam('scope'); - return activatedRouteSnapshot.queryParams[scopeParam] || activatedRouteSnapshot.queryParams.scope; - } - /** * Find a DSpaceObject in one of the provided route snapshots their data * Recursively looks for the dso in the routes their child routes until it reaches a dead end or finds one From 9346a91426f232fa0b4427329bf23719f7b7ae40 Mon Sep 17 00:00:00 2001 From: Ali Jaber Date: Sun, 30 Aug 2026 21:19:40 -0400 Subject: [PATCH 7/9] 143851: avoid eager search configuration dependencies --- .../top-level-community-list.component.spec.ts | 2 ++ .../shared/geospatial-map/geospatial-map.component.ts | 10 ++++++---- src/app/shared/rss-feed/rss.component.ts | 10 +++++++++- src/app/shared/theme-support/theme.service.ts | 4 ++-- 4 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/app/home-page/top-level-community-list/top-level-community-list.component.spec.ts b/src/app/home-page/top-level-community-list/top-level-community-list.component.spec.ts index 3b397846ccb..99ebfe2b900 100644 --- a/src/app/home-page/top-level-community-list/top-level-community-list.component.spec.ts +++ b/src/app/home-page/top-level-community-list/top-level-community-list.component.spec.ts @@ -25,6 +25,7 @@ import { PageInfo } from '../../core/shared/page-info.model'; import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service'; import { HostWindowService } from '../../shared/host-window.service'; import { getMockThemeService } from '../../shared/mocks/theme-service.mock'; +import { CommunityListElementComponent } from '../../shared/object-list/community-list-element/community-list-element.component'; import { SelectableListService } from '../../shared/object-list/selectable-list/selectable-list.service'; import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; import { HostWindowServiceStub } from '../../shared/testing/host-window-service.stub'; @@ -148,6 +149,7 @@ describe('TopLevelCommunityListComponent', () => { RouterTestingModule.withRoutes([]), NgbModule, NoopAnimationsModule, + CommunityListElementComponent, TopLevelCommunityListComponent, ], providers: [ diff --git a/src/app/shared/geospatial-map/geospatial-map.component.ts b/src/app/shared/geospatial-map/geospatial-map.component.ts index 29afd577493..afd4b0f4157 100644 --- a/src/app/shared/geospatial-map/geospatial-map.component.ts +++ b/src/app/shared/geospatial-map/geospatial-map.component.ts @@ -4,6 +4,7 @@ import { Component, ElementRef, Inject, + Injector, Input, OnDestroy, OnInit, @@ -102,7 +103,7 @@ export class GeospatialMapComponent implements AfterViewInit, OnInit, OnDestroy @Inject(PLATFORM_ID) private platformId: string, private router: Router, private translateService: TranslateService, - private searchConfigurationService: SearchConfigurationService) { + private injector: Injector) { } ngOnInit() { @@ -284,11 +285,12 @@ export class GeospatialMapComponent implements AfterViewInit, OnInit, OnDestroy direction: 'top', }).on('click', () => { // On click, make a filtered search using the point filter ('f.point' by default) + const searchConfigurationService = this.injector.get(SearchConfigurationService); void this.router.navigate([point.url], { queryParams: { - [this.searchConfigurationService.getCurrentPageParam()]: 1, - [this.searchConfigurationService.getCurrentSearchInstanceFilterParam(filter)]: point.value + ',equals', - [this.searchConfigurationService.getCurrentSearchInstanceParam('scope')]: this.currentScope, + [searchConfigurationService.getCurrentPageParam()]: 1, + [searchConfigurationService.getCurrentSearchInstanceFilterParam(filter)]: point.value + ',equals', + [searchConfigurationService.getCurrentSearchInstanceParam('scope')]: this.currentScope, } }); }); markers.addLayer(marker); diff --git a/src/app/shared/rss-feed/rss.component.ts b/src/app/shared/rss-feed/rss.component.ts index 48cb5fd350c..d05cc052f86 100644 --- a/src/app/shared/rss-feed/rss.component.ts +++ b/src/app/shared/rss-feed/rss.component.ts @@ -3,10 +3,12 @@ import { ChangeDetectionStrategy, Component, Inject, + Injector, Input, OnChanges, OnDestroy, OnInit, + Optional, SimpleChanges, ViewEncapsulation, } from '@angular/core'; @@ -68,14 +70,18 @@ export class RSSComponent implements OnInit, OnDestroy, OnChanges { subs: Subscription[] = []; openSearchUri: string; + private searchConfigurationService: SearchConfigurationService; + constructor(private groupDataService: GroupDataService, private linkHeadService: LinkHeadService, private configurationService: ConfigurationDataService, - @Inject(SEARCH_CONFIG_SERVICE) private searchConfigurationService: SearchConfigurationService, + @Optional() @Inject(SEARCH_CONFIG_SERVICE) searchConfigurationService: SearchConfigurationService, + private injector: Injector, private router: Router, private route: ActivatedRoute, protected paginationService: PaginationService, protected translateService: TranslateService) { + this.searchConfigurationService = searchConfigurationService; } ngOnDestroy(): void { @@ -86,6 +92,8 @@ export class RSSComponent implements OnInit, OnDestroy, OnChanges { } ngOnInit(): void { + this.searchConfigurationService = this.searchConfigurationService ?? this.injector.get(SearchConfigurationService); + // Set initial activation state if (hasValue(this.route.snapshot.data?.enableRSS)) { this.isActivated$.next(this.route.snapshot.data.enableRSS); diff --git a/src/app/shared/theme-support/theme.service.ts b/src/app/shared/theme-support/theme.service.ts index ac8eac53b71..9856e4ab0e7 100644 --- a/src/app/shared/theme-support/theme.service.ts +++ b/src/app/shared/theme-support/theme.service.ts @@ -106,7 +106,6 @@ export class ThemeService { @Inject(GET_THEME_CONFIG_FOR_FACTORY) private gtcf: (str) => ThemeConfig, private router: Router, @Inject(DOCUMENT) private document: any, - private searchConfigurationService: SearchConfigurationService, @Optional() private hashedFileMapping: HashedFileMapping, ) { // Create objects from the theme configs in the environment file @@ -366,7 +365,8 @@ export class ThemeService { ); } } - const scope = this.searchConfigurationService.getSearchParamFromParams(activatedRouteSnapshot.queryParams, 'scope'); + const searchConfigurationService = this.injector.get(SearchConfigurationService); + const scope = searchConfigurationService.getSearchParamFromParams(activatedRouteSnapshot.queryParams, 'scope'); if (hasValue(scope)) { const dsoFromScope$: Observable> = this.dSpaceObjectDataService.findById(scope); // Start with the resolved dso and go recursively through its parents until you reach the top-level community From 55828f247ae7fe34f23faa10ee2e06b8c34c71df Mon Sep 17 00:00:00 2001 From: Ali Jaber Date: Wed, 23 Sep 2026 21:06:18 -0400 Subject: [PATCH 8/9] 143851: use scoped search configuration for view mode switching --- .../search-configuration.service.spec.ts | 48 +++++++++++++++++++ .../search/search-configuration.service.ts | 19 ++++++++ .../search-configuration-service.stub.ts | 10 +++- .../view-mode-switch.component.spec.ts | 8 +++- .../view-mode-switch.component.ts | 11 +++-- 5 files changed, 90 insertions(+), 6 deletions(-) diff --git a/src/app/core/shared/search/search-configuration.service.spec.ts b/src/app/core/shared/search/search-configuration.service.spec.ts index 890de831184..8daac606101 100644 --- a/src/app/core/shared/search/search-configuration.service.spec.ts +++ b/src/app/core/shared/search/search-configuration.service.spec.ts @@ -24,6 +24,7 @@ import { } from '../../cache/models/sort-options.model'; import { RemoteData } from '../../data/remote-data'; import { RequestEntry } from '../../data/request-entry.model'; +import { ViewMode } from '../view-mode.model'; import { SearchConfigurationService } from './search-configuration.service'; describe('SearchConfigurationService', () => { @@ -173,6 +174,53 @@ describe('SearchConfigurationService', () => { }); }); + describe('when setViewMode is called', () => { + beforeEach(() => { + service.searchInstanceId = 'custom-search'; + paginationService.getCurrentPagination.and.returnValue(of( + Object.assign(new PaginationComponentOptions(), { pageSize: 20 }), + )); + paginationService.updateRouteWithUrl.calls.reset(); + }); + + it('should update the scoped view parameter and reset the page', () => { + service.setViewMode(ViewMode.GridElement, ['search']); + + expect(paginationService.updateRouteWithUrl).toHaveBeenCalledWith( + 'custom-search', + ['search'], + { page: 1 }, + { 'custom-search.view': ViewMode.GridElement }, + ); + }); + + it('should use a page size of one for the detailed list view', () => { + service.setViewMode(ViewMode.DetailedListElement, []); + + expect(paginationService.updateRouteWithUrl).toHaveBeenCalledWith( + 'custom-search', + [], + { page: 1, pageSize: 1 }, + { 'custom-search.view': ViewMode.DetailedListElement }, + ); + }); + + it('should restore the default page size when leaving the detailed list view', () => { + paginationService.getCurrentPagination.and.returnValue(of( + Object.assign(new PaginationComponentOptions(), { pageSize: 1 }), + )); + + service.setViewMode(ViewMode.ListElement, []); + + expect(paginationService.updateRouteWithUrl).toHaveBeenCalledWith( + 'custom-search', + [], + { page: 1, pageSize: 10 }, + { 'custom-search.view': ViewMode.ListElement }, + ); + }); + }); + describe('when subscribeToSearchOptions or subscribeToPaginatedSearchOptions is called', () => { beforeEach(() => { spyOn(service, 'getCurrentPagination').and.callThrough(); diff --git a/src/app/core/shared/search/search-configuration.service.ts b/src/app/core/shared/search/search-configuration.service.ts index 332b9900d74..7d012bf7e5d 100644 --- a/src/app/core/shared/search/search-configuration.service.ts +++ b/src/app/core/shared/search/search-configuration.service.ts @@ -316,6 +316,25 @@ export class SearchConfigurationService implements OnDestroy { })); } + /** + * Changes the current view mode in the current URL + * @param viewMode Mode to switch to + * @param searchLinkParts Route segments used for the navigation + */ + setViewMode(viewMode: ViewMode, searchLinkParts: string[]): void { + this.paginationService.getCurrentPagination(this.searchInstanceId, new PaginationComponentOptions()).pipe(take(1)) + .subscribe((config) => { + let pageParams = { page: 1 }; + const queryParams = { [this.getCurrentSearchInstanceParam('view')]: viewMode }; + if (viewMode === ViewMode.DetailedListElement) { + pageParams = Object.assign(pageParams, { pageSize: 1 }); + } else if (config.pageSize === 1) { + pageParams = Object.assign(pageParams, { pageSize: 10 }); + } + this.paginationService.updateRouteWithUrl(this.searchInstanceId, searchLinkParts, pageParams, queryParams); + }); + } + /** * Creates an observable of SearchConfig every time the configuration stream emits. * @param configuration The search configuration diff --git a/src/app/shared/testing/search-configuration-service.stub.ts b/src/app/shared/testing/search-configuration-service.stub.ts index e898777c39d..b25007a78f5 100644 --- a/src/app/shared/testing/search-configuration-service.stub.ts +++ b/src/app/shared/testing/search-configuration-service.stub.ts @@ -24,6 +24,7 @@ export class SearchConfigurationServiceStub { public searchOptions: BehaviorSubject = new BehaviorSubject(new SearchOptions({})); public paginatedSearchOptions: BehaviorSubject = new BehaviorSubject(new PaginatedSearchOptions({})); + private viewMode: BehaviorSubject = new BehaviorSubject(undefined); getCurrentFrontendFilters() { return of([]); @@ -62,7 +63,14 @@ export class SearchConfigurationServiceStub { } getCurrentViewMode(defaultViewMode: ViewMode) { - return of(defaultViewMode); + if (this.viewMode.value === undefined) { + this.viewMode.next(defaultViewMode); + } + return this.viewMode.asObservable(); + } + + setViewMode(viewMode: ViewMode) { + this.viewMode.next(viewMode); } getConfigurationAdvancedSearchFilters(_configuration: string, _scope?: string): Observable { diff --git a/src/app/shared/view-mode-switch/view-mode-switch.component.spec.ts b/src/app/shared/view-mode-switch/view-mode-switch.component.spec.ts index 2f8eb0d9aca..5e10804d5d9 100644 --- a/src/app/shared/view-mode-switch/view-mode-switch.component.spec.ts +++ b/src/app/shared/view-mode-switch/view-mode-switch.component.spec.ts @@ -18,7 +18,9 @@ import { import { SearchService } from '../../core/shared/search/search.service'; import { ViewMode } from '../../core/shared/view-mode.model'; +import { SEARCH_CONFIG_SERVICE } from '../../my-dspace-page/my-dspace-configuration.service'; import { TranslateLoaderMock } from '../mocks/translate-loader.mock'; +import { SearchConfigurationServiceStub } from '../testing/search-configuration-service.stub'; import { SearchServiceStub } from '../testing/search-service.stub'; import { ViewModeSwitchComponent } from './view-mode-switch.component'; @@ -32,6 +34,7 @@ describe('ViewModeSwitchComponent', () => { let comp: ViewModeSwitchComponent; let fixture: ComponentFixture; const searchService = new SearchServiceStub(); + const searchConfigurationService = new SearchConfigurationServiceStub(); let listButton: HTMLElement; let gridButton: HTMLElement; let detailButton: HTMLElement; @@ -52,6 +55,7 @@ describe('ViewModeSwitchComponent', () => { ], providers: [ { provide: SearchService, useValue: searchService }, + { provide: SEARCH_CONFIG_SERVICE, useValue: searchConfigurationService }, ], }).overrideComponent(ViewModeSwitchComponent, { set: { changeDetection: ChangeDetectionStrategy.Default }, @@ -68,7 +72,7 @@ describe('ViewModeSwitchComponent', () => { beforeEach(fakeAsync(() => { comp.viewModeList = [ViewMode.ListElement, ViewMode.GridElement]; comp.currentMode = ViewMode.ListElement; - searchService.setViewMode(ViewMode.ListElement); + searchConfigurationService.setViewMode(ViewMode.ListElement); tick(); fixture.detectChanges(); const debugElements = fixture.debugElement.queryAll(By.css('button')); @@ -103,7 +107,7 @@ describe('ViewModeSwitchComponent', () => { beforeEach(fakeAsync(() => { comp.viewModeList = [ViewMode.ListElement, ViewMode.DetailedListElement]; comp.currentMode = ViewMode.ListElement; - searchService.setViewMode(ViewMode.ListElement); + searchConfigurationService.setViewMode(ViewMode.ListElement); tick(); fixture.detectChanges(); const debugElements = fixture.debugElement.queryAll(By.css('button')); diff --git a/src/app/shared/view-mode-switch/view-mode-switch.component.ts b/src/app/shared/view-mode-switch/view-mode-switch.component.ts index 21149f18fab..510c59bdaa3 100644 --- a/src/app/shared/view-mode-switch/view-mode-switch.component.ts +++ b/src/app/shared/view-mode-switch/view-mode-switch.component.ts @@ -2,6 +2,7 @@ import { Component, EventEmitter, + Inject, Input, OnDestroy, OnInit, @@ -18,7 +19,9 @@ import { filter } from 'rxjs/operators'; import { environment } from '../../../environments/environment'; import { SearchService } from '../../core/shared/search/search.service'; +import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service'; import { ViewMode } from '../../core/shared/view-mode.model'; +import { SEARCH_CONFIG_SERVICE } from '../../my-dspace-page/my-dspace-configuration.service'; import { isEmpty, isNotEmpty, @@ -73,7 +76,9 @@ export class ViewModeSwitchComponent implements OnInit, OnDestroy { */ @Output() changeViewMode: EventEmitter = new EventEmitter(); - constructor(private searchService: SearchService, private router: Router) { + constructor(private searchService: SearchService, + private router: Router, + @Inject(SEARCH_CONFIG_SERVICE) private searchConfigurationService: SearchConfigurationService) { } /** @@ -87,7 +92,7 @@ export class ViewModeSwitchComponent implements OnInit, OnDestroy { } } - this.sub = this.searchService.getViewMode().pipe( + this.sub = this.searchConfigurationService.getCurrentViewMode(ViewMode.ListElement).pipe( filter((viewMode: ViewMode) => isNotEmpty(viewMode)), ).subscribe((viewMode: ViewMode) => { this.currentMode = viewMode; @@ -102,7 +107,7 @@ export class ViewModeSwitchComponent implements OnInit, OnDestroy { if (viewMode !== this.currentMode) { this.changeViewMode.emit(viewMode); } - this.searchService.setViewMode(viewMode, this.getSearchLinkParts()); + this.searchConfigurationService.setViewMode(viewMode, this.getSearchLinkParts()); } ngOnDestroy() { From afa8f542e48b783c2996839084a89f8ae2404be8 Mon Sep 17 00:00:00 2001 From: Ali Jaber Date: Fri, 16 Oct 2026 00:07:06 -0400 Subject: [PATCH 9/9] 143851: scope search filter UI state per search instance The collapsed/expanded state and facet page of search filters were stored by filter name only, so multiple searches on the same page (e.g. exhibit search blocks) shared that state. Resetting the filters of one search re-initialized the filter panels of every other search with the same filter names, hiding their selected values. The state keys are now prefixed with the search instance id. Also pass inPlaceSearch to the small-screen search sidebar, so its filter and "Reset filters" links stay on the current page instead of going to /search. --- .../search/search-filter.service.spec.ts | 28 ++++++++++ .../shared/search/search-filter.service.ts | 55 +++++++++++++------ .../search-facet-filter.component.spec.ts | 6 +- .../search-facet-filter.component.ts | 6 +- .../search-filter/search-filter.actions.ts | 4 +- .../search-filter.component.spec.ts | 4 +- .../search-filter/search-filter.component.ts | 8 +-- .../search-filter.reducer.spec.ts | 17 ++++++ .../testing/search-filter-service.stub.ts | 18 +++--- 9 files changed, 105 insertions(+), 41 deletions(-) diff --git a/src/app/core/shared/search/search-filter.service.spec.ts b/src/app/core/shared/search/search-filter.service.spec.ts index a19917d6810..2b83755f27d 100644 --- a/src/app/core/shared/search/search-filter.service.spec.ts +++ b/src/app/core/shared/search/search-filter.service.spec.ts @@ -138,6 +138,34 @@ describe('SearchFilterService', () => { }); }); + describe('when a search instance id is provided', () => { + const searchInstanceId = 'test-instance'; + const scopedFilterName = `${searchInstanceId}.${filterName1}`; + + it('should scope the filter state key to the search instance', () => { + expect(service.getFilterStateKey(filterName1, searchInstanceId)).toEqual(scopedFilterName); + expect(service.getFilterStateKey(filterName1)).toEqual(filterName1); + }); + + it('should dispatch the filter state actions for the scoped filter state key', () => { + service.initializeFilter(mockFilterConfig, searchInstanceId); + service.collapse(filterName1, searchInstanceId); + service.expand(filterName1, searchInstanceId); + service.toggle(filterName1, searchInstanceId); + service.decrementPage(filterName1, searchInstanceId); + service.incrementPage(filterName1, searchInstanceId); + service.resetPage(filterName1, searchInstanceId); + + expect(store.dispatch as jasmine.Spy).toHaveBeenCalledWith(new SearchFilterInitializeAction(mockFilterConfig, scopedFilterName)); + expect(store.dispatch as jasmine.Spy).toHaveBeenCalledWith(new SearchFilterCollapseAction(scopedFilterName)); + expect(store.dispatch as jasmine.Spy).toHaveBeenCalledWith(new SearchFilterExpandAction(scopedFilterName)); + expect(store.dispatch as jasmine.Spy).toHaveBeenCalledWith(new SearchFilterToggleAction(scopedFilterName)); + expect(store.dispatch as jasmine.Spy).toHaveBeenCalledWith(new SearchFilterDecrementPageAction(scopedFilterName)); + expect(store.dispatch as jasmine.Spy).toHaveBeenCalledWith(new SearchFilterIncrementPageAction(scopedFilterName)); + expect(store.dispatch as jasmine.Spy).toHaveBeenCalledWith(new SearchFilterResetPageAction(scopedFilterName)); + }); + }); + describe('when the isFilterActiveWithValue method is called', () => { beforeEach(() => { spyOn(routeServiceStub, 'hasQueryParamWithValue'); diff --git a/src/app/core/shared/search/search-filter.service.ts b/src/app/core/shared/search/search-filter.service.ts index a36b593b876..ccf9409b45a 100644 --- a/src/app/core/shared/search/search-filter.service.ts +++ b/src/app/core/shared/search/search-filter.service.ts @@ -239,14 +239,25 @@ export class SearchFilterService { return this.routeService.getQueryParameterValue(parameterName); } + /** + * Get the key under which the UI state (collapsed, page) of a filter is stored. When a search instance id is + * provided, the key is scoped to that instance so multiple searches on the same page don't share their filter state. + * @param {string} filterName The filter name + * @param {string} searchInstanceId The optional search instance id + */ + getFilterStateKey(filterName: string, searchInstanceId?: string): string { + return hasValue(searchInstanceId) ? this.getSearchInstanceParam(searchInstanceId, filterName) : filterName; + } + /** * Checks if the state of a given filter is currently collapsed or not * @param {string} filterName The filtername for which the collapsed state is checked + * @param {string} searchInstanceId The optional search instance id the filter belongs to * @returns {Observable} Emits the current collapsed state of the given filter, if it's unavailable, return false */ - isCollapsed(filterName: string): Observable { + isCollapsed(filterName: string, searchInstanceId?: string): Observable { return this.store.pipe( - select(filterByNameSelector(filterName)), + select(filterByNameSelector(this.getFilterStateKey(filterName, searchInstanceId))), map((object: SearchFilterState) => { if (object) { return object.filterCollapsed || object.minimized; @@ -261,11 +272,12 @@ export class SearchFilterService { /** * Request the current page of a given filter * @param {string} filterName The filter name for which the page state is checked + * @param {string} searchInstanceId The optional search instance id the filter belongs to * @returns {Observable} Emits the current page state of the given filter, if it's unavailable, return 1 */ - getPage(filterName: string): Observable { + getPage(filterName: string, searchInstanceId?: string): Observable { return this.store.pipe( - select(filterByNameSelector(filterName)), + select(filterByNameSelector(this.getFilterStateKey(filterName, searchInstanceId))), map((object: SearchFilterState) => { if (object) { return object.page; @@ -279,57 +291,64 @@ export class SearchFilterService { /** * Dispatches a collapse action to the store for a given filter * @param {string} filterName The filter for which the action is dispatched + * @param {string} searchInstanceId The optional search instance id the filter belongs to */ - public collapse(filterName: string): void { - this.store.dispatch(new SearchFilterCollapseAction(filterName)); + public collapse(filterName: string, searchInstanceId?: string): void { + this.store.dispatch(new SearchFilterCollapseAction(this.getFilterStateKey(filterName, searchInstanceId))); } /** * Dispatches an expand action to the store for a given filter * @param {string} filterName The filter for which the action is dispatched + * @param {string} searchInstanceId The optional search instance id the filter belongs to */ - public expand(filterName: string): void { - this.store.dispatch(new SearchFilterExpandAction(filterName)); + public expand(filterName: string, searchInstanceId?: string): void { + this.store.dispatch(new SearchFilterExpandAction(this.getFilterStateKey(filterName, searchInstanceId))); } /** * Dispatches a toggle action to the store for a given filter * @param {string} filterName The filter for which the action is dispatched + * @param {string} searchInstanceId The optional search instance id the filter belongs to */ - public toggle(filterName: string): void { - this.store.dispatch(new SearchFilterToggleAction(filterName)); + public toggle(filterName: string, searchInstanceId?: string): void { + this.store.dispatch(new SearchFilterToggleAction(this.getFilterStateKey(filterName, searchInstanceId))); } /** * Dispatches an initialize action to the store for a given filter * @param {SearchFilterConfig} filter The filter for which the action is dispatched + * @param {string} searchInstanceId The optional search instance id the filter belongs to */ - public initializeFilter(filter: SearchFilterConfig): void { - this.store.dispatch(new SearchFilterInitializeAction(filter)); + public initializeFilter(filter: SearchFilterConfig, searchInstanceId?: string): void { + this.store.dispatch(new SearchFilterInitializeAction(filter, this.getFilterStateKey(filter.name, searchInstanceId))); } /** * Dispatches a decrement action to the store for a given filter * @param {string} filterName The filter for which the action is dispatched + * @param {string} searchInstanceId The optional search instance id the filter belongs to */ - public decrementPage(filterName: string): void { - this.store.dispatch(new SearchFilterDecrementPageAction(filterName)); + public decrementPage(filterName: string, searchInstanceId?: string): void { + this.store.dispatch(new SearchFilterDecrementPageAction(this.getFilterStateKey(filterName, searchInstanceId))); } /** * Dispatches an increment page action to the store for a given filter * @param {string} filterName The filter for which the action is dispatched + * @param {string} searchInstanceId The optional search instance id the filter belongs to */ - public incrementPage(filterName: string): void { - this.store.dispatch(new SearchFilterIncrementPageAction(filterName)); + public incrementPage(filterName: string, searchInstanceId?: string): void { + this.store.dispatch(new SearchFilterIncrementPageAction(this.getFilterStateKey(filterName, searchInstanceId))); } /** * Dispatches a reset page action to the store for a given filter * @param {string} filterName The filter for which the action is dispatched + * @param {string} searchInstanceId The optional search instance id the filter belongs to */ - public resetPage(filterName: string): void { - this.store.dispatch(new SearchFilterResetPageAction(filterName)); + public resetPage(filterName: string, searchInstanceId?: string): void { + this.store.dispatch(new SearchFilterResetPageAction(this.getFilterStateKey(filterName, searchInstanceId))); } public minimizeAll(): void { diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter/search-facet-filter.component.spec.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter/search-facet-filter.component.spec.ts index 5ea39f4d539..10bdd0ffbb1 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter/search-facet-filter.component.spec.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter/search-facet-filter.component.spec.ts @@ -139,7 +139,7 @@ describe('SearchFacetFilterComponent', () => { }); it('should call incrementPage on the filterService with the correct filter parameter name', () => { - expect(filterService.incrementPage).toHaveBeenCalledWith(mockFilterConfig.name); + expect(filterService.incrementPage).toHaveBeenCalledWith(mockFilterConfig.name, 'test-id'); }); }); @@ -150,7 +150,7 @@ describe('SearchFacetFilterComponent', () => { }); it('should call resetPage on the filterService with the correct filter parameter name', () => { - expect(filterService.resetPage).toHaveBeenCalledWith(mockFilterConfig.name); + expect(filterService.resetPage).toHaveBeenCalledWith(mockFilterConfig.name, 'test-id'); }); }); @@ -161,7 +161,7 @@ describe('SearchFacetFilterComponent', () => { }); it('should call getPage on the filterService with the correct filter parameter name', () => { - expect(filterService.getPage).toHaveBeenCalledWith(mockFilterConfig.name); + expect(filterService.getPage).toHaveBeenCalledWith(mockFilterConfig.name, 'test-id'); }); }); diff --git a/src/app/shared/search/search-filters/search-filter/search-facet-filter/search-facet-filter.component.ts b/src/app/shared/search/search-filters/search-filter/search-facet-filter/search-facet-filter.component.ts index bf5e8d79e9a..41250644b4d 100644 --- a/src/app/shared/search/search-filters/search-filter/search-facet-filter/search-facet-filter.component.ts +++ b/src/app/shared/search/search-filters/search-filter/search-facet-filter/search-facet-filter.component.ts @@ -206,21 +206,21 @@ export class SearchFacetFilterComponent implements OnInit, OnDestroy { * Show the next page as well */ showMore() { - this.filterService.incrementPage(this.filterConfig.name); + this.filterService.incrementPage(this.filterConfig.name, this.searchConfigService.searchInstanceId); } /** * Make sure only the first page is shown */ showFirstPageOnly() { - this.filterService.resetPage(this.filterConfig.name); + this.filterService.resetPage(this.filterConfig.name, this.searchConfigService.searchInstanceId); } /** * @returns {Observable} The current page of this filter */ getCurrentPage(): Observable { - return this.filterService.getPage(this.filterConfig.name); + return this.filterService.getPage(this.filterConfig.name, this.searchConfigService.searchInstanceId); } /** diff --git a/src/app/shared/search/search-filters/search-filter/search-filter.actions.ts b/src/app/shared/search/search-filters/search-filter/search-filter.actions.ts index e8d8cee8e67..18bb0e3af64 100644 --- a/src/app/shared/search/search-filters/search-filter/search-filter.actions.ts +++ b/src/app/shared/search/search-filters/search-filter/search-filter.actions.ts @@ -70,8 +70,8 @@ export class SearchFilterToggleAction extends SearchFilterAction { export class SearchFilterInitializeAction extends SearchFilterAction { type = SearchFilterActionTypes.INITIALIZE; initiallyExpanded; - constructor(filter: SearchFilterConfig) { - super(filter.name); + constructor(filter: SearchFilterConfig, filterName: string = filter.name) { + super(filterName); this.initiallyExpanded = filter.isOpenByDefault; } } diff --git a/src/app/shared/search/search-filters/search-filter/search-filter.component.spec.ts b/src/app/shared/search/search-filters/search-filter/search-filter.component.spec.ts index 125713e76e4..1a44550f0a2 100644 --- a/src/app/shared/search/search-filters/search-filter/search-filter.component.spec.ts +++ b/src/app/shared/search/search-filters/search-filter/search-filter.component.spec.ts @@ -101,7 +101,7 @@ describe('SearchFilterComponent', () => { }); it('should call toggle with the correct filter configuration name', () => { - expect(searchFilterService.toggle).toHaveBeenCalledWith(mockFilterConfig.name); + expect(searchFilterService.toggle).toHaveBeenCalledWith(mockFilterConfig.name, 'test-id'); }); }); @@ -112,7 +112,7 @@ describe('SearchFilterComponent', () => { }); it('should call initialCollapse with the correct filter configuration name', () => { - expect(searchFilterService.initializeFilter).toHaveBeenCalledWith(mockFilterConfig); + expect(searchFilterService.initializeFilter).toHaveBeenCalledWith(mockFilterConfig, 'test-id'); }); }); diff --git a/src/app/shared/search/search-filters/search-filter/search-filter.component.ts b/src/app/shared/search/search-filters/search-filter/search-filter.component.ts index 8b05ec59400..e27dc529bba 100644 --- a/src/app/shared/search/search-filters/search-filter/search-filter.component.ts +++ b/src/app/shared/search/search-filters/search-filter/search-filter.component.ts @@ -147,7 +147,7 @@ export class SearchFilterComponent implements OnInit, OnChanges, OnDestroy { this.subs.push( this.appliedFilters$.subscribe((selectedValues: AppliedFilter[]) => { if (isNotEmpty(selectedValues)) { - this.filterService.expand(this.filter.name); + this.filterService.expand(this.filter.name, this.searchConfigService.searchInstanceId); } }), this.getIsActive().subscribe(() => { @@ -170,7 +170,7 @@ export class SearchFilterComponent implements OnInit, OnChanges, OnDestroy { * Changes the state for this filter to collapsed when it's expanded and to expanded it when it's collapsed */ toggle() { - this.filterService.toggle(this.filter.name); + this.filterService.toggle(this.filter.name, this.searchConfigService.searchInstanceId); } /** @@ -178,14 +178,14 @@ export class SearchFilterComponent implements OnInit, OnChanges, OnDestroy { * @returns {Observable} Emits true when the current state of the filter is collapsed, false when it's expanded */ private isCollapsed(): Observable { - return this.filterService.isCollapsed(this.filter.name); + return this.filterService.isCollapsed(this.filter.name, this.searchConfigService.searchInstanceId); } /** * Sets the initial state of the filter */ initializeFilter() { - this.filterService.initializeFilter(this.filter); + this.filterService.initializeFilter(this.filter, this.searchConfigService.searchInstanceId); } /** diff --git a/src/app/shared/search/search-filters/search-filter/search-filter.reducer.spec.ts b/src/app/shared/search/search-filters/search-filter/search-filter.reducer.spec.ts index eff66dd3a4e..5c6de7753fa 100644 --- a/src/app/shared/search/search-filters/search-filter/search-filter.reducer.spec.ts +++ b/src/app/shared/search/search-filters/search-filter/search-filter.reducer.spec.ts @@ -182,4 +182,21 @@ describe('filterReducer', () => { const newState = filterReducer(state, action); expect(newState[filterName1].page).toEqual(1); }); + + it('should only update the state of the given search instance when the filter name is scoped by search instance', () => { + const instance1FilterName = `instance-1.${filterName1}`; + const instance2FilterName = `instance-2.${filterName1}`; + const state = {}; + state[instance1FilterName] = { filterCollapsed: true, minimized: false, page: 1 }; + state[instance2FilterName] = { filterCollapsed: false, minimized: false, page: 3 }; + deepFreeze([state]); + + const filterConfig = { isOpenByDefault: false, name: filterName1 } as any; + let newState = filterReducer(state, new SearchFilterInitializeAction(filterConfig, instance1FilterName)); + newState = filterReducer(newState, new SearchFilterToggleAction(instance1FilterName)); + newState = filterReducer(newState, new SearchFilterResetPageAction(instance1FilterName)); + + expect(newState[instance1FilterName]).toEqual({ filterCollapsed: false, minimized: false, page: 1 }); + expect(newState[instance2FilterName]).toEqual({ filterCollapsed: false, minimized: false, page: 3 }); + }); }); diff --git a/src/app/shared/testing/search-filter-service.stub.ts b/src/app/shared/testing/search-filter-service.stub.ts index 4fbe0999960..2273dd0a730 100644 --- a/src/app/shared/testing/search-filter-service.stub.ts +++ b/src/app/shared/testing/search-filter-service.stub.ts @@ -49,33 +49,33 @@ export class SearchFilterServiceStub { return of(undefined); } - isCollapsed(_filterName: string): Observable { + isCollapsed(_filterName: string, _searchInstanceId?: string): Observable { return of(true); } - getPage(_filterName: string): Observable { + getPage(_filterName: string, _searchInstanceId?: string): Observable { return of(1); } - collapse(_filterName: string): void { + collapse(_filterName: string, _searchInstanceId?: string): void { } - expand(_filterName: string): void { + expand(_filterName: string, _searchInstanceId?: string): void { } - toggle(_filterName: string): void { + toggle(_filterName: string, _searchInstanceId?: string): void { } - initializeFilter(_filter: SearchFilterConfig): void { + initializeFilter(_filter: SearchFilterConfig, _searchInstanceId?: string): void { } - decrementPage(_filterName: string): void { + decrementPage(_filterName: string, _searchInstanceId?: string): void { } - incrementPage(_filterName: string): void { + incrementPage(_filterName: string, _searchInstanceId?: string): void { } - resetPage(_filterName: string): void { + resetPage(_filterName: string, _searchInstanceId?: string): void { } minimizeAll(): void {