Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[libs, ME]: persist records selection #669

Merged
merged 6 commits into from
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
</div>
<div class="flex flex-row gap-3 items-center">
<h1 class="text-[56px] font-title grow">{{ title }}</h1>
np
<h1 *ngIf="users" class="text-[56px] font-title grow" translate>
dashboard.records.users
</h1>
Expand Down Expand Up @@ -64,8 +63,11 @@ <h1 *ngIf="users" class="text-[56px] font-title grow" translate>
[records]="results"
[totalHits]="users ? users.length : (searchFacade.resultsHits$ | async)"
(recordSelect)="editRecord($event)"
(recordsDeselection)="handleRecordsDeselection($event)"
(recordsSelection)="handleRecordsSelection($event)"
(sortByChange)="setSortBy($event)"
[sortBy]="searchFacade.sortBy$ | async"
[selectedRecords]="getSelectedRecords() | async"
></gn-ui-record-table>
<div
class="px-5 py-5 flex justify-center gap-8 items-baseline"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { Router } from '@angular/router'
import { BehaviorSubject } from 'rxjs'
import { CommonModule } from '@angular/common'
import { MatIconModule } from '@angular/material/icon'
import { SelectionService } from '@geonetwork-ui/api/repository/gn4'

const results = [{ md: true }]
const currentPage = 5
Expand All @@ -23,6 +24,7 @@ export class RecordTableComponent {
@Input() records: CatalogRecord[]
@Input() totalHits: number
@Output() recordSelect = new EventEmitter<CatalogRecord>()
Copy link
Collaborator

Choose a reason for hiding this comment

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

See my other comment about event names, this might deserve a clarification as well :)

@Output() recordsSelection = new EventEmitter<CatalogRecord[]>()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is this output really needed? I didn't see any use of it

}

@Component({
Expand Down Expand Up @@ -55,12 +57,19 @@ class RouterMock {
navigate = jest.fn()
}

class SelectionServiceMock {
selectRecords = jest.fn()
deselectRecords = jest.fn()
clearSelection = jest.fn()
}

describe('RecordsListComponent', () => {
let component: RecordsListComponent
let fixture: ComponentFixture<RecordsListComponent>
let router: Router
let searchService: SearchService
let searchFacade: SearchFacade
let selectionService: SelectionService

beforeEach(() => {
TestBed.configureTestingModule({
Expand All @@ -77,6 +86,10 @@ describe('RecordsListComponent', () => {
provide: SearchService,
useClass: SearchServiceMock,
},
{
provide: SelectionService,
useClass: SelectionServiceMock,
},
],
}).overrideComponent(RecordsListComponent, {
set: {
Expand All @@ -90,6 +103,7 @@ describe('RecordsListComponent', () => {
})
router = TestBed.inject(Router)
searchService = TestBed.inject(SearchService)
selectionService = TestBed.inject(SelectionService)
searchFacade = TestBed.inject(SearchFacade)
fixture = TestBed.createComponent(RecordsListComponent)
component = fixture.componentInstance
Expand Down Expand Up @@ -121,10 +135,15 @@ describe('RecordsListComponent', () => {
describe('when click on a record', () => {
beforeEach(() => {
table.recordSelect.emit({ uniqueIdentifier: 123 })
table.recordsSelection.emit([{ uniqueIdentifier: 123 }])
Copy link
Collaborator

Choose a reason for hiding this comment

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

This deserves a separate test I think there should be a distinction between "clicking on a record" and "selecting a record"

})
it('routes to record edition', () => {
expect(router.navigate).toHaveBeenCalledWith(['/edit', 123])
})

it('persists selection', () => {
expect(selectionService.selectRecords).toHaveBeenCalled()
})
})
describe('when click on pagination', () => {
beforeEach(() => {
Expand Down
34 changes: 31 additions & 3 deletions apps/metadata-editor/src/app/records/records-list.component.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common'
import { Component, Input } from '@angular/core'
import { Component, Input, OnDestroy } from '@angular/core'
import { MatIconModule } from '@angular/material/icon'
import { Router } from '@angular/router'
import { CatalogRecord } from '@geonetwork-ui/common/domain/record'
Expand All @@ -8,6 +8,8 @@ import { UiSearchModule } from '@geonetwork-ui/ui/search'
import { UiElementsModule } from '@geonetwork-ui/ui/elements'
import { SortByField } from '@geonetwork-ui/common/domain/search'
import { TranslateModule } from '@ngx-translate/core'
import { SelectionService } from '@geonetwork-ui/api/repository/gn4'
import { Subject, takeUntil } from 'rxjs'

const includes = [
'uuid',
Expand All @@ -34,18 +36,21 @@ const includes = [
TranslateModule,
],
})
export class RecordsListComponent {
export class RecordsListComponent implements OnDestroy {
@Input() title: string
@Input() logo: string
@Input() recordCount: number
@Input() userCount: number
@Input() users
@Input() linkToDatahub?: string

private onDestroy$: Subject<void> = new Subject()

constructor(
private router: Router,
public searchFacade: SearchFacade,
public searchService: SearchService
public searchService: SearchService,
private selectionService: SelectionService
) {
this.searchFacade.setPageSize(15).setConfigRequestFields(includes)
}
Expand All @@ -72,4 +77,27 @@ export class RecordsListComponent {
showUsers() {
this.router.navigate(['/users/my-org'])
}

getSelectedRecords() {
return this.selectionService.selectedRecordsIdentifiers$
}

handleRecordsSelection(records: CatalogRecord[]) {
this.selectionService
.selectRecords(records)
.pipe(takeUntil(this.onDestroy$))
Copy link
Collaborator

Choose a reason for hiding this comment

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

Interesting, that looks like a valid approach to avoid having long-running observables stopping after a component is destroyed. Here though we shouldn't need it as the selectRecords and deselectRecords of the service are built on top of HTTP calls, which means they are short-lived observables and will complete after their first emission.

.subscribe()
}

handleRecordsDeselection(records: CatalogRecord[]) {
this.selectionService
.deselectRecords(records)
.pipe(takeUntil(this.onDestroy$))
.subscribe()
}

ngOnDestroy(): void {
this.onDestroy$.next()
this.onDestroy$.complete()
}
}
1 change: 1 addition & 0 deletions libs/api/repository/src/lib/gn4/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ export * from './elasticsearch'
export * from './settings/gn4-settings.service'
export * from './auth'
export * from './favorites/favorites.service'
export * from './selection/selection.service'
107 changes: 107 additions & 0 deletions libs/api/repository/src/lib/gn4/selection/selection.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { SelectionsApiService } from '@geonetwork-ui/data-access/gn4'
import { SelectionService } from './selection.service'
import { firstValueFrom, of } from 'rxjs'
import { CatalogRecord } from '@geonetwork-ui/common/domain/record'

function record(uuid: string): CatalogRecord {
return {
uniqueIdentifier: uuid,
} as CatalogRecord
}

class SelectionsServiceMock {
private selected = ['001', '002', '003']
add = jest.fn((bucket, ids) => {
this.selected.push(...ids)
return of(undefined)
})
clear = jest.fn((bucket, ids) => {
this.selected = this.selected.filter(
(id) => !!ids && ids.indexOf(id) === -1
)
return of(undefined)
})
get = jest.fn(() => of(this.selected))
}

describe('SelectionService', () => {
let service: SelectionService
let selectionsService: SelectionsApiService

beforeEach(async () => {
selectionsService = new SelectionsServiceMock() as any
service = new SelectionService(selectionsService)
})

it('should be created', () => {
expect(service).toBeTruthy()
})

describe('#selectRecords', () => {
let selectedRecords
beforeEach(async () => {
service.selectedRecordsIdentifiers$.subscribe((value) => {
selectedRecords = value
})
await firstValueFrom(
service.selectRecords([record('abcd'), record('efgh'), record('001')])
)
})
it('calls the corresponding API', () => {
expect(selectionsService.add).toHaveBeenCalledWith('gnui', [
'abcd',
'efgh',
'001',
])
})
it('emits new records in selectedRecordsIdentifiers$', () => {
expect(selectedRecords).toEqual(['001', '002', '003', 'abcd', 'efgh'])
})
})

describe('#deselectRecords', () => {
let selectedRecords
beforeEach(async () => {
service.selectedRecordsIdentifiers$.subscribe((value) => {
selectedRecords = value
})
await firstValueFrom(
service.deselectRecords([record('abcd'), record('efgh'), record('001')])
)
})
it('calls the corresponding API', () => {
expect(selectionsService.clear).toHaveBeenCalledWith('gnui', [
'abcd',
'efgh',
'001',
])
})
it('emits new records in selectedRecordsIdentifiers$', () => {
expect(selectedRecords).toEqual(['002', '003'])
})
})

describe('#clearSelection', () => {
let selectedRecords
beforeEach(async () => {
service.selectedRecordsIdentifiers$.subscribe((value) => {
selectedRecords = value
})
await firstValueFrom(service.clearSelection())
})
it('calls the corresponding API', () => {
expect(selectionsService.get).toHaveBeenCalledWith('gnui')

expect(selectionsService.clear).toHaveBeenCalledWith('gnui', [
'001',
'002',
'003',
])
})
it('emits new records in selectedRecordsIdentifiers$', () => {
expect(selectedRecords).toEqual([])
})
})

// describe('selectedRecordsIdentifiers$', () => {})
})
80 changes: 80 additions & 0 deletions libs/api/repository/src/lib/gn4/selection/selection.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { Injectable } from '@angular/core'
import { CatalogRecord } from '@geonetwork-ui/common/domain/record'
import { SelectionsApiService } from '@geonetwork-ui/data-access/gn4'
import { BehaviorSubject, Observable, Subscription, map, tap } from 'rxjs'

const BUCKET_ID = 'gnui'

@Injectable({
providedIn: 'root',
})
export class SelectionService {
selectedRecordsIdentifiers$: BehaviorSubject<string[]> = new BehaviorSubject(
[]
)
subscription: Subscription

constructor(private selectionsApi: SelectionsApiService) {
this.selectionsApi.get(BUCKET_ID).subscribe((selectedIds) => {
this.addIdsToSelected(Array.from(selectedIds))
})
}

private addIdsToSelected(ids: string[]) {
const currentIds = this.selectedRecordsIdentifiers$.value
const uniqueSet = new Set([...currentIds, ...ids])
this.selectedRecordsIdentifiers$.next([...uniqueSet])
}

private removeIdsFromSelected(ids: string[]) {
const filtered = this.selectedRecordsIdentifiers$.value.filter(
(value) => !ids.includes(value)
)
this.selectedRecordsIdentifiers$.next(filtered)
}

selectRecords(records: CatalogRecord[]): Observable<void> {
const newIds = []
records.map((record) => {
newIds.push(record.uniqueIdentifier)
})
const apiResponse = this.selectionsApi.add(BUCKET_ID, newIds)
return apiResponse.pipe(
tap(() => {
this.addIdsToSelected(newIds)
}),
map(() => undefined)
)
}

deselectRecords(records: CatalogRecord[]): Observable<void> {
const idsToBeRemoved = []
records.map((record) => {
idsToBeRemoved.push(record.uniqueIdentifier)
})
const apiResponse = this.selectionsApi.clear(BUCKET_ID, idsToBeRemoved)
return apiResponse.pipe(
tap(() => {
this.removeIdsFromSelected(idsToBeRemoved)
}),
map(() => undefined)
)
}

clearSelection(): Observable<void> {
const currentSelectedResponse = this.selectionsApi.get(BUCKET_ID)
let currentSelection
this.subscription = currentSelectedResponse.subscribe((value) => {
currentSelection = [...value]
})
this.selectionsApi.clear(BUCKET_ID, currentSelection)
const apiResponse = this.selectionsApi.clear(BUCKET_ID, currentSelection)

return apiResponse.pipe(
tap(() => {
this.removeIdsFromSelected(currentSelection)
}),
map(() => undefined)
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ describe('RecordTableComponent', () => {
})
})

describe('isChecked', () => {
describe('#isChecked', () => {
it('should return true when the record is in the selectedRecords array', () => {
const component = new RecordTableComponent()
component.selectedRecords = ['1', '2', '3']
Expand Down
Loading
Loading