This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-5215-d08645529119db0d12cf4f1466f6b5a2db6d5eb5 in repository https://gitbox.apache.org/repos/asf/texera.git
commit 223a27b2929cff6b164030eea385fe143ba51791 Author: Xuan Gu <[email protected]> AuthorDate: Mon Jun 1 19:50:24 2026 -0700 feat(dashboard): add public dataset card view (#5215) <!-- Thanks for sending a pull request (PR)! Here are some tips for you: 1. If this is your first time, please read our contributor guidelines: [Contributing to Texera](https://github.com/apache/texera/blob/main/CONTRIBUTING.md) 2. Ensure you have added or run the appropriate tests for your PR 3. If the PR is work in progress, mark it a draft on GitHub. 4. Please write your PR title to summarize what this PR proposes, we are following Conventional Commits style for PR titles as well. 5. Be sure to keep the PR description updated to reflect all changes. --> ### What changes were proposed in this PR? <!-- Please clarify what changes you are proposing. The purpose of this section is to outline the changes. Here are some tips for you: 1. If you propose a new API, clarify the use case for a new API. 2. If you fix a bug, you can clarify why it is a bug. 3. If it is a refactoring, clarify what has been changed. 3. It would be helpful to include a before-and-after comparison using screenshots or GIFs. 4. Please consider writing useful notes for better and faster reviews. --> This PR adds a card view to the dataset listing, with a toggle to switch between the existing list view and the new card view for public dataset. Applied to the public dataset listing (/dashboard/hub/dataset/result). Changes: - Added DatasetCardItemComponent (frontend/.../user/dataset-card-item/, renders a dataset card with cover image, title, owner avatar + name, last-updated time, size, view count, and a like button. View mode persists per-user via localStorage. - Decoupled SearchResultsComponent from any specific card component. It now accepts a cardTemplate: TemplateRef input, allowing each consumer to provide its own card via <ng-template> projection. The card branch is gated on viewMode === 'card' && cardTemplate. - The card loads cover images through the existing presigned-URL endpoint GET /dataset/{did}/cover-url, so covers render via a plain <img src> without attaching a JWT header (works for public datasets and for private datasets the requester has access to). - Reused the shared formatCount ("1.5k" style) and formatRelativeTime ("5 minutes ago" style) utilities. - Added HubService.toggleLike helper, encapsulating the like/unlike + refresh-count flow. - Projected DATASET.COVER_IMAGE through UnifiedResourceSchema and DatasetSearchQueryBuilder so search responses include the cover path needed by the card. <img width="1561" height="775" alt="public-dataset" src="https://github.com/user-attachments/assets/23b84f3f-a39e-4ffa-98a5-67f39d48a626" /> ### Any related issues, documentation, discussions? <!-- Please use this section to link other resources if not mentioned already. 1. If this PR fixes an issue, please include `Fixes #1234`, `Resolves #1234` or `Closes #1234`. If it is only related, simply mention the issue number. 3. If there is design documentation, please add the link. 4. If there is a discussion in the mailing list, please add the link. --> Discussion #5130 Related to #4216 (workflow card view; same framework can later be applied). Closes #5243 ### How was this PR tested? <!-- If tests were added, say they were added here. Or simply mention that if the PR is tested with existing test cases. Make sure to include/update test cases that check the changes thoroughly including negative and positive cases if possible. If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future. If tests were not added, please describe why they were not added and/or why it was difficult to add. --> Added test cases and manually tested. ### Was this PR authored or co-authored using generative AI tooling? <!-- If generative AI tooling has been used in the process of authoring this PR, please include the phrase: 'Generated-by: ' followed by the name of the tool and its version. If no, write 'No'. Please refer to the [ASF Generative Tooling Guidance](https://www.apache.org/legal/generative-tooling.html) for details. --> Generated-by: Claude Opus 4.7 --------- Signed-off-by: Xuan Gu <[email protected]> Co-authored-by: Matthew B. <[email protected]> --- .../dashboard/DatasetSearchQueryBuilder.scala | 3 +- .../resource/dashboard/UnifiedResourceSchema.scala | 6 +- .../dataset-card-item.component.html | 101 +++++++++++ .../dataset-card-item.component.scss | 198 +++++++++++++++++++++ .../dataset-card-item.component.spec.ts | 158 ++++++++++++++++ .../dataset-card-item.component.ts | 134 ++++++++++++++ .../search-results/search-results.component.html | 80 ++++++--- .../search-results/search-results.component.scss | 18 ++ .../search-results/search-results.component.ts | 11 +- .../hub-search-result.component.html | 41 ++++- .../hub-search-result.component.scss | 35 ++++ .../hub-search-result.component.ts | 31 +++- frontend/src/app/hub/service/hub.service.ts | 21 +++ 13 files changed, 801 insertions(+), 36 deletions(-) diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/DatasetSearchQueryBuilder.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/DatasetSearchQueryBuilder.scala index 89fe805d58..64c8c31106 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/DatasetSearchQueryBuilder.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/DatasetSearchQueryBuilder.scala @@ -48,7 +48,8 @@ object DatasetSearchQueryBuilder extends SearchQueryBuilder with LazyLogging { repositoryName = DATASET.REPOSITORY_NAME, isDatasetPublic = DATASET.IS_PUBLIC, isDatasetDownloadable = DATASET.IS_DOWNLOADABLE, - datasetUserAccess = DATASET_USER_ACCESS.PRIVILEGE + datasetUserAccess = DATASET_USER_ACCESS.PRIVILEGE, + datasetCoverImage = DATASET.COVER_IMAGE ) /* diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/UnifiedResourceSchema.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/UnifiedResourceSchema.scala index dbcf192640..8c4ecda946 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/UnifiedResourceSchema.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/UnifiedResourceSchema.scala @@ -72,7 +72,8 @@ object UnifiedResourceSchema { repositoryName: Field[String] = DSL.inline(""), isDatasetPublic: Field[java.lang.Boolean] = DSL.cast(null, classOf[java.lang.Boolean]), isDatasetDownloadable: Field[java.lang.Boolean] = DSL.cast(null, classOf[java.lang.Boolean]), - datasetUserAccess: Field[PrivilegeEnum] = DSL.castNull(classOf[PrivilegeEnum]) + datasetUserAccess: Field[PrivilegeEnum] = DSL.castNull(classOf[PrivilegeEnum]), + datasetCoverImage: Field[String] = DSL.cast(null, classOf[String]) ): UnifiedResourceSchema = { new UnifiedResourceSchema( Seq( @@ -96,7 +97,8 @@ object UnifiedResourceSchema { repositoryName -> repositoryName.as("repository_name"), isDatasetPublic -> isDatasetPublic.as("is_dataset_public"), isDatasetDownloadable -> isDatasetDownloadable.as("is_dataset_downloadable"), - datasetUserAccess -> datasetUserAccess.as("user_dataset_access") + datasetUserAccess -> datasetUserAccess.as("user_dataset_access"), + datasetCoverImage -> datasetCoverImage.as("cover_image") ) ) } diff --git a/frontend/src/app/dashboard/component/user/dataset-card-item/dataset-card-item.component.html b/frontend/src/app/dashboard/component/user/dataset-card-item/dataset-card-item.component.html new file mode 100644 index 0000000000..205e3848f3 --- /dev/null +++ b/frontend/src/app/dashboard/component/user/dataset-card-item/dataset-card-item.component.html @@ -0,0 +1,101 @@ +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<nz-card + nzHoverable + class="dataset-card" + [nzCover]="coverTpl" + [routerLink]="entryLink"> + <div class="dataset-card-body-link"> + <span + class="card-title" + [title]="entry.name"> + {{ entry.name }} + </span> + + <div class="card-meta"> + <div class="meta-line meta-line--owner"> + <span + class="meta-owner" + [title]="entry.ownerName || entry.ownerEmail || 'Unknown'"> + <texera-user-avatar + class="meta-avatar" + [googleAvatar]="entry.ownerGoogleAvatar" + userColor="#1E90FF" + [userName]="entry.ownerName || entry.ownerEmail || 'Unknown'" + [isOwner]="entry.ownerId === currentUid"> + </texera-user-avatar> + <span class="meta-owner-name truncate-single-line"> + {{ entry.ownerName || entry.ownerEmail || 'Unknown' }} + </span> + </span> + <span + class="meta-dot" + aria-hidden="true" + >·</span + > + <span class="meta-updated">Created {{ formatRelativeTime(entry.lastModifiedTime) }}</span> + </div> + <div class="meta-hr"></div> + <div class="meta-line meta-line--stats"> + <div class="meta-stats-left"> + <span class="meta-stat"> + <i + nz-icon + nzType="database" + nzTheme="outline"></i> + {{ entry.size ? formatSize(entry.size) : '-' }} + </span> + <span class="meta-stat"> + <i + nz-icon + nzType="eye" + nzTheme="outline"></i> + {{ formatCount(viewCount) }} + </span> + </div> + <button + type="button" + class="meta-stat meta-stat--like" + [class.liked]="isLiked" + [class.disabled]="!currentUid" + (click)="$event.stopPropagation(); $event.preventDefault(); currentUid && toggleLike()"> + <i + nz-icon + nzType="like" + [nzTheme]="isLiked ? 'fill' : 'outline'"></i> + {{ formatCount(likeCount) }} + </button> + </div> + </div> + </div> +</nz-card> + +<ng-template #coverTpl> + <div class="cover-container"> + <img + class="cover-image" + [src]="coverImageSrc" + (error)="onCoverError($event)" + loading="lazy" + decoding="async" + alt="dataset cover" /> + <span class="cover-id-badge">#{{ entry.id }}</span> + </div> +</ng-template> diff --git a/frontend/src/app/dashboard/component/user/dataset-card-item/dataset-card-item.component.scss b/frontend/src/app/dashboard/component/user/dataset-card-item/dataset-card-item.component.scss new file mode 100644 index 0000000000..60f4e15913 --- /dev/null +++ b/frontend/src/app/dashboard/component/user/dataset-card-item/dataset-card-item.component.scss @@ -0,0 +1,198 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +.dataset-card { + height: 100%; + display: flex; + flex-direction: column; + border-radius: 8px; + overflow: hidden; + cursor: pointer; +} + +.dataset-card-body-link { + display: flex; + flex: 1; + flex-direction: column; + min-height: 0; + color: inherit; +} + +.cover-container { + position: relative; + height: 124px; + background: #f5f5f5; + overflow: hidden; + + .cover-image { + width: 100%; + height: 100%; + object-fit: cover; + display: block; + } + + .cover-id-badge { + position: absolute; + left: 8px; + bottom: 8px; + padding: 2px 8px; + font-size: 12px; + border-radius: 12px; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15); + background: rgba(15, 14, 12, 0.72); + color: white; + } +} + +.card-title { + display: -webkit-box; + height: calc(15px * 1.35 * 2); + margin-bottom: 10px; + font-size: 15px; + font-weight: 600; + line-height: 1.35; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + overflow: hidden; + word-break: break-word; +} + +.truncate-single-line { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.card-meta { + display: flex; + flex-direction: column; + gap: 5px; + margin-top: auto; + padding-top: 4px; + min-width: 0; + + .meta-line { + display: flex; + align-items: center; + gap: 6px; + color: #595959; + min-width: 0; + + &--owner { + font-size: 13px; + + .meta-owner { + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 0; + } + + .meta-avatar { + flex-shrink: 0; + + ::ng-deep nz-avatar.ant-avatar { + width: 20px; + height: 20px; + line-height: 20px; + font-size: 10px; + } + ::ng-deep .owner-badge { + font-size: 9px; + } + } + + .meta-dot { + flex-shrink: 0; + color: #bfbfbf; + font-size: 13px; + line-height: 1; + user-select: none; + } + + .meta-updated { + flex-shrink: 0; + font-size: 12px; + color: #8c8c8c; + white-space: nowrap; + } + } + + &--stats { + justify-content: space-between; + font-size: 12px; + color: #8c8c8c; + } + + .meta-stat { + display: inline-flex; + align-items: center; + gap: 4px; + flex-shrink: 0; + white-space: nowrap; + + i { + font-size: 12px; + } + } + + .meta-stat--like { + padding: 0 10px; + border: 1px solid #e8e8e8; + border-radius: 999px; + background: transparent; + color: inherit; + font-size: 12px; + gap: 8px; + cursor: pointer; + transition: border-color 0.15s; + + i { + font-size: 11px; + transition: color 0.15s; + } + + &.liked i, + &:not(.disabled):not(.liked):hover i { + color: #e0506e; + } + + &:not(.disabled):hover { + border-color: #e0506e; + } + + &.disabled { + cursor: default; + } + } + } + + .meta-stats-left { + display: inline-flex; + align-items: center; + gap: 12px; + min-width: 0; + } + + .meta-hr { + height: 1px; + background: #f0f0f0; + margin: 2px 0; + } +} diff --git a/frontend/src/app/dashboard/component/user/dataset-card-item/dataset-card-item.component.spec.ts b/frontend/src/app/dashboard/component/user/dataset-card-item/dataset-card-item.component.spec.ts new file mode 100644 index 0000000000..1ca8248441 --- /dev/null +++ b/frontend/src/app/dashboard/component/user/dataset-card-item/dataset-card-item.component.spec.ts @@ -0,0 +1,158 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { ComponentFixture, TestBed } from "@angular/core/testing"; +import { HttpClientTestingModule } from "@angular/common/http/testing"; +import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; +import { RouterTestingModule } from "@angular/router/testing"; +import { of, throwError } from "rxjs"; +import type { Mocked } from "vitest"; + +import { DatasetCardItemComponent } from "./dataset-card-item.component"; +import { DashboardEntry } from "src/app/dashboard/type/dashboard-entry"; +import { DatasetService } from "../../../service/user/dataset/dataset.service"; +import { HubService } from "../../../../hub/service/hub.service"; +import { UserService } from "../../../../common/service/user/user.service"; +import { StubUserService } from "../../../../common/service/user/stub-user.service"; +import { HUB_DATASET_RESULT_DETAIL, USER_DATASET } from "../../../../app-routing.constant"; +import { commonTestProviders } from "../../../../common/testing/test-utils"; + +function makeDatasetEntry(overrides: Partial<any> = {}): DashboardEntry { + return { + type: "dataset", + id: 42, + accessibleUserIds: [1, 2], + coverImageUrl: undefined, + likeCount: 5, + isLiked: false, + ...overrides, + } as unknown as DashboardEntry; +} + +describe("DatasetCardItemComponent", () => { + let component: DatasetCardItemComponent; + let fixture: ComponentFixture<DatasetCardItemComponent>; + let hubService: Mocked<HubService>; + + beforeEach(async () => { + const hubServiceSpy = { + toggleLike: vi.fn().mockReturnValue(of({ liked: true, likeCount: 7 })), + }; + + await TestBed.configureTestingModule({ + imports: [DatasetCardItemComponent, HttpClientTestingModule, BrowserAnimationsModule, RouterTestingModule], + providers: [ + { + provide: DatasetService, + useValue: { + getDatasetCoverUrl: vi.fn().mockReturnValue(of({ url: "https://s3.example/presigned" })), + }, + }, + { provide: HubService, useValue: hubServiceSpy }, + { provide: UserService, useClass: StubUserService }, + ...commonTestProviders, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(DatasetCardItemComponent); + component = fixture.componentInstance; + hubService = TestBed.inject(HubService) as unknown as Mocked<HubService>; + }); + + describe("entryLink", () => { + it("routes to the private dataset page when the current user has access", () => { + component.currentUid = 1; + component.entry = makeDatasetEntry({ id: 99, accessibleUserIds: [1, 2] }); + component.ngOnChanges({ entry: { currentValue: component.entry } } as any); + expect(component.entryLink).toEqual([USER_DATASET, "99"]); + }); + + it("routes to the hub detail page when the current user has no access", () => { + component.currentUid = 5; + component.entry = makeDatasetEntry({ id: 99, accessibleUserIds: [1, 2] }); + component.ngOnChanges({ entry: { currentValue: component.entry } } as any); + expect(component.entryLink).toEqual([HUB_DATASET_RESULT_DETAIL, "99"]); + }); + }); + + describe("coverImageSrc", () => { + it("falls back to the default cover when coverImageUrl is missing", () => { + const datasetService = TestBed.inject(DatasetService) as unknown as Mocked<DatasetService>; + component.entry = makeDatasetEntry({ coverImageUrl: undefined }); + component.ngOnChanges({ entry: { currentValue: component.entry } } as any); + expect(component.coverImageSrc).toBe(component.defaultCover); + expect(datasetService.getDatasetCoverUrl).not.toHaveBeenCalled(); + }); + + it("swaps in the presigned URL once the backend resolves it", () => { + const datasetService = TestBed.inject(DatasetService) as unknown as Mocked<DatasetService>; + component.entry = makeDatasetEntry({ id: 7, coverImageUrl: "v1/img.png" }); + component.ngOnChanges({ entry: { currentValue: component.entry } } as any); + expect(datasetService.getDatasetCoverUrl).toHaveBeenCalledWith(7); + expect(component.coverImageSrc).toBe("https://s3.example/presigned"); + }); + + it("falls back to the default cover when the backend returns a null url", () => { + const datasetService = TestBed.inject(DatasetService) as unknown as Mocked<DatasetService>; + datasetService.getDatasetCoverUrl.mockReturnValueOnce(of({ url: null })); + component.entry = makeDatasetEntry({ id: 9, coverImageUrl: "v1/img.png" }); + component.ngOnChanges({ entry: { currentValue: component.entry } } as any); + expect(component.coverImageSrc).toBe(component.defaultCover); + }); + + it("falls back to the default cover when the backend errors", () => { + const datasetService = TestBed.inject(DatasetService) as unknown as Mocked<DatasetService>; + datasetService.getDatasetCoverUrl.mockReturnValueOnce(throwError(() => new Error("403"))); + component.entry = makeDatasetEntry({ id: 11, coverImageUrl: "v1/img.png" }); + component.ngOnChanges({ entry: { currentValue: component.entry } } as any); + expect(component.coverImageSrc).toBe(component.defaultCover); + }); + }); + + describe("toggleLike", () => { + beforeEach(() => { + component.currentUid = 1; + component.entry = makeDatasetEntry(); + component.ngOnChanges({ entry: { currentValue: component.entry } } as any); + }); + + it("does nothing when the user is not signed in", () => { + component.currentUid = undefined; + component.toggleLike(); + expect(hubService.toggleLike).not.toHaveBeenCalled(); + }); + + it("toggles to liked and reconciles state from the server", () => { + component.isLiked = false; + component.toggleLike(); + expect(hubService.toggleLike).toHaveBeenCalledWith(42, "dataset", false); + expect(component.isLiked).toBe(true); + expect(component.likeCount).toBe(7); + }); + + it("toggles to unliked and reconciles state from the server", () => { + hubService.toggleLike.mockReturnValueOnce(of({ liked: false, likeCount: 6 })); + component.isLiked = true; + component.toggleLike(); + expect(hubService.toggleLike).toHaveBeenCalledWith(42, "dataset", true); + expect(component.isLiked).toBe(false); + expect(component.likeCount).toBe(6); + }); + }); +}); diff --git a/frontend/src/app/dashboard/component/user/dataset-card-item/dataset-card-item.component.ts b/frontend/src/app/dashboard/component/user/dataset-card-item/dataset-card-item.component.ts new file mode 100644 index 0000000000..5e9fd3e27f --- /dev/null +++ b/frontend/src/app/dashboard/component/user/dataset-card-item/dataset-card-item.component.ts @@ -0,0 +1,134 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnChanges, SimpleChanges } from "@angular/core"; +import { UntilDestroy, untilDestroyed } from "@ngneat/until-destroy"; +import { RouterLink } from "@angular/router"; +import { NzCardComponent } from "ng-zorro-antd/card"; +import { NzIconDirective } from "ng-zorro-antd/icon"; +import { DashboardEntry } from "../../../type/dashboard-entry"; +import { UserAvatarComponent } from "../user-avatar/user-avatar.component"; +import { DatasetService } from "../../../service/user/dataset/dataset.service"; +import { HubService } from "../../../../hub/service/hub.service"; +import { formatSize } from "../../../../common/util/size-formatter.util"; +import { formatCount, formatRelativeTime } from "../../../../common/util/format.util"; +import { isDefined } from "../../../../common/util/predicate"; +import { HUB_DATASET_RESULT_DETAIL, USER_DATASET } from "../../../../app-routing.constant"; + +@UntilDestroy() +@Component({ + selector: "texera-dataset-card-item", + templateUrl: "./dataset-card-item.component.html", + styleUrls: ["./dataset-card-item.component.scss"], + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [RouterLink, NzCardComponent, NzIconDirective, UserAvatarComponent], +}) +export class DatasetCardItemComponent implements OnChanges { + @Input() currentUid: number | undefined; + @Input() entry!: DashboardEntry; + + entryLink: string[] = []; + coverImageSrc: string = ""; + readonly defaultCover = "assets/card_background.jpg"; + likeCount = 0; + viewCount = 0; + isLiked = false; + + constructor( + private datasetService: DatasetService, + private hubService: HubService, + private cdr: ChangeDetectorRef + ) {} + + ngOnChanges(changes: SimpleChanges): void { + if (changes["entry"] || changes["currentUid"]) { + this.initializeEntry(); + } + if (changes["entry"]) { + this.likeCount = this.entry.likeCount ?? 0; + this.viewCount = this.entry.viewCount ?? 0; + this.isLiked = this.entry.isLiked ?? false; + } + } + + private initializeEntry(): void { + if (!this.entry || this.entry.type !== "dataset" || typeof this.entry.id !== "number") { + return; + } + const did = this.entry.id; + const owners = this.entry.accessibleUserIds; + if (this.currentUid !== undefined && owners.includes(this.currentUid)) { + this.entryLink = [USER_DATASET, String(did)]; + } else { + this.entryLink = [HUB_DATASET_RESULT_DETAIL, String(did)]; + } + + this.coverImageSrc = this.defaultCover; + if (this.entry.coverImageUrl) { + this.datasetService + .getDatasetCoverUrl(did) + .pipe(untilDestroyed(this)) + .subscribe({ + next: ({ url }) => { + this.coverImageSrc = url ?? this.defaultCover; + this.cdr.markForCheck(); + }, + error: () => { + this.coverImageSrc = this.defaultCover; + this.cdr.markForCheck(); + }, + }); + } + } + + onCoverError(event: Event): void { + const image = event.target as HTMLImageElement; + image.onerror = null; + image.src = this.defaultCover; + } + + toggleLike(): void { + if (!isDefined(this.currentUid) || !isDefined(this.entry.id)) return; + // optimistic flip; server response reconciles or reverts + const previousLiked = this.isLiked; + this.isLiked = !previousLiked; + this.likeCount += previousLiked ? -1 : 1; + this.cdr.markForCheck(); + + this.hubService + .toggleLike(this.entry.id, this.entry.type, previousLiked) + .pipe(untilDestroyed(this)) + .subscribe({ + next: ({ liked, likeCount }) => { + this.isLiked = liked; + this.likeCount = likeCount; + this.cdr.markForCheck(); + }, + error: () => { + this.isLiked = previousLiked; + this.likeCount += previousLiked ? 1 : -1; + this.cdr.markForCheck(); + }, + }); + } + + formatSize = formatSize; + formatCount = formatCount; + formatRelativeTime = formatRelativeTime; +} diff --git a/frontend/src/app/dashboard/component/user/search-results/search-results.component.html b/frontend/src/app/dashboard/component/user/search-results/search-results.component.html index d623b98153..084ccb0d9f 100644 --- a/frontend/src/app/dashboard/component/user/search-results/search-results.component.html +++ b/frontend/src/app/dashboard/component/user/search-results/search-results.component.html @@ -20,36 +20,60 @@ <nz-card class="section-list-container" [nzBodyStyle]="{ height: '100%'}"> - <!-- itemSize: the height (px) of each list item, + <!-- LIST VIEW --> + <ng-container *ngIf="viewMode === 'list'"> + <!-- itemSize: the height (px) of each list item, this MUST be approximately the same as list item size set in CSS, .workflow-list-item sets the item size to be 70px, with additional paddings/margins it's approximately 80px --> - <cdk-virtual-scroll-viewport - itemSize="70" - class="virtual-scroll-container"> - <nz-list> - <ng-container *ngFor="let entry of entries"> - <texera-list-item - (deleted)="deleted.emit(entry)" - (duplicated)="duplicated.emit(entry)" - (refresh)="refresh.emit()" - [isPrivateSearch]="isPrivateSearch" - [editable]="editable" - [entry]="entry" - [currentUid]="this.currentUid" - (checkboxChanged)="onEntryCheckboxChange()"> - </texera-list-item> - </ng-container> - </nz-list> - <div - nz-list-load-more - class="load-more"> - <button - nz-button - *ngIf="!loading && more" - (click)="loadMore()"> - Load more - </button> + <cdk-virtual-scroll-viewport + itemSize="70" + class="virtual-scroll-container"> + <nz-list> + <ng-container *ngFor="let entry of entries"> + <texera-list-item + (deleted)="deleted.emit(entry)" + (duplicated)="duplicated.emit(entry)" + (refresh)="refresh.emit()" + [isPrivateSearch]="isPrivateSearch" + [editable]="editable" + [entry]="entry" + [currentUid]="this.currentUid" + (checkboxChanged)="onEntryCheckboxChange()"> + </texera-list-item> + </ng-container> + </nz-list> + <div + nz-list-load-more + class="load-more"> + <button + nz-button + *ngIf="!loading && more" + (click)="loadMore()"> + Load more + </button> + </div> + </cdk-virtual-scroll-viewport> + </ng-container> + + <!-- CARD VIEW --> + <ng-container *ngIf="viewMode === 'card' && cardTemplate"> + <div class="card-scroll-container"> + <div class="card-grid"> + <ng-container + *ngFor="let entry of entries; trackBy: trackByEntryId" + [ngTemplateOutlet]="cardTemplate" + [ngTemplateOutletContext]="{ $implicit: entry }"> + </ng-container> + </div> + <div class="load-more"> + <button + nz-button + *ngIf="!loading && more" + (click)="loadMore()"> + Load more + </button> + </div> </div> - </cdk-virtual-scroll-viewport> + </ng-container> </nz-card> diff --git a/frontend/src/app/dashboard/component/user/search-results/search-results.component.scss b/frontend/src/app/dashboard/component/user/search-results/search-results.component.scss index 73ccb3127a..1f113d6e5a 100644 --- a/frontend/src/app/dashboard/component/user/search-results/search-results.component.scss +++ b/frontend/src/app/dashboard/component/user/search-results/search-results.component.scss @@ -130,3 +130,21 @@ nz-content { margin: 0 1rem 0 0; // add space to the right } } + +.card-scroll-container { + height: 100%; + overflow-y: auto; + padding: 12px; +} + +.card-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); + gap: 10px; + justify-content: start; + align-items: stretch; + + > * { + max-width: 300px; + } +} diff --git a/frontend/src/app/dashboard/component/user/search-results/search-results.component.ts b/frontend/src/app/dashboard/component/user/search-results/search-results.component.ts index 601a6534a5..baddea9f68 100644 --- a/frontend/src/app/dashboard/component/user/search-results/search-results.component.ts +++ b/frontend/src/app/dashboard/component/user/search-results/search-results.component.ts @@ -17,13 +17,13 @@ * under the License. */ -import { Component, EventEmitter, Input, Output } from "@angular/core"; +import { Component, EventEmitter, Input, Output, TemplateRef } from "@angular/core"; import { DashboardEntry } from "../../../type/dashboard-entry"; import { UserService } from "../../../../common/service/user/user.service"; import { NzCardComponent } from "ng-zorro-antd/card"; import { ɵɵCdkVirtualScrollViewport, ɵɵCdkFixedSizeVirtualScroll } from "@angular/cdk/overlay"; import { NzListComponent } from "ng-zorro-antd/list"; -import { NgFor, NgIf } from "@angular/common"; +import { NgFor, NgIf, NgTemplateOutlet } from "@angular/common"; import { ListItemComponent } from "../list-item/list-item.component"; import { NzSpaceCompactItemDirective } from "ng-zorro-antd/space"; import { NzButtonComponent } from "ng-zorro-antd/button"; @@ -31,6 +31,7 @@ import { NzWaveDirective } from "ng-zorro-antd/core/wave"; import { ɵNzTransitionPatchDirective } from "ng-zorro-antd/core/transition-patch"; export type LoadMoreFunction = (start: number, count: number) => Promise<{ entries: DashboardEntry[]; more: boolean }>; +export type SearchResultsViewMode = "list" | "card"; @Component({ selector: "texera-search-results", @@ -44,6 +45,7 @@ export type LoadMoreFunction = (start: number, count: number) => Promise<{ entri NgFor, ListItemComponent, NgIf, + NgTemplateOutlet, NzSpaceCompactItemDirective, NzButtonComponent, NzWaveDirective, @@ -62,6 +64,11 @@ export class SearchResultsComponent { @Input() editable = false; @Input() searchKeywords: string[] = []; @Input() currentUid: number | undefined; + @Input() viewMode: SearchResultsViewMode = "list"; + /** Template rendered for each entry in card mode; receives the entry via $implicit. */ + @Input() cardTemplate?: TemplateRef<{ $implicit: DashboardEntry }>; + + trackByEntryId = (_: number, entry: DashboardEntry): string => `${entry.type}-${entry.id}`; @Output() deleted = new EventEmitter<DashboardEntry>(); @Output() duplicated = new EventEmitter<DashboardEntry>(); @Output() modified = new EventEmitter<DashboardEntry>(); diff --git a/frontend/src/app/hub/component/hub-search-result/hub-search-result.component.html b/frontend/src/app/hub/component/hub-search-result/hub-search-result.component.html index 1ce36ff5ab..b910262df7 100644 --- a/frontend/src/app/hub/component/hub-search-result/hub-search-result.component.html +++ b/frontend/src/app/hub/component/hub-search-result/hub-search-result.component.html @@ -22,14 +22,53 @@ <div class="filter"> <texera-sort-button (sortMethodChange)="sortMethod = $event; search()"></texera-sort-button> <texera-filters #filters></texera-filters> + <div + *ngIf="searchType === 'dataset'" + class="view-toggle"> + <button + nz-button + nzType="text" + [class.active]="viewMode === 'list'" + (click)="setViewMode('list')" + nz-tooltip="List view" + title="List view"> + <i + nz-icon + nzType="bars" + nzTheme="outline"></i> + </button> + <button + nz-button + nzType="text" + [class.active]="viewMode === 'card'" + (click)="setViewMode('card')" + nz-tooltip="Card view" + title="Card view"> + <i + nz-icon + nzType="table" + nzTheme="outline"></i> + </button> + </div> </div> </div> + <ng-template + #datasetCardTpl + let-entry> + <texera-dataset-card-item + [entry]="entry" + [currentUid]="currentUid"> + </texera-dataset-card-item> + </ng-template> + <div class="search-result"> <texera-search-results [showResourceTypes]="true" [searchKeywords]="searchKeywords" - [currentUid]="this.currentUid"> + [currentUid]="this.currentUid" + [viewMode]="searchType === 'dataset' ? viewMode : 'list'" + [cardTemplate]="searchType === 'dataset' ? datasetCardTpl : undefined"> </texera-search-results> </div> </div> diff --git a/frontend/src/app/hub/component/hub-search-result/hub-search-result.component.scss b/frontend/src/app/hub/component/hub-search-result/hub-search-result.component.scss index e172c5b40b..15c6777275 100644 --- a/frontend/src/app/hub/component/hub-search-result/hub-search-result.component.scss +++ b/frontend/src/app/hub/component/hub-search-result/hub-search-result.component.scss @@ -18,3 +18,38 @@ */ @import "../../../dashboard/component/user/search/search.component"; + +.filter { + flex: 1; + display: flex; + align-items: center; + gap: 8px; +} + +.view-toggle { + display: inline-flex; + background: #f5f5f5; + border-radius: 6px; + padding: 2px; + margin-left: auto; + + button { + height: 28px; + padding: 0 10px; + border: none; + background: transparent; + color: #8c8c8c; + border-radius: 4px; + + &:hover { + color: #595959; + background: rgba(255, 255, 255, 0.6); + } + + &.active { + background: #fff; + color: #1f1f1f; + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08); + } + } +} diff --git a/frontend/src/app/hub/component/hub-search-result/hub-search-result.component.ts b/frontend/src/app/hub/component/hub-search-result/hub-search-result.component.ts index 067e920562..1f69bdcff7 100644 --- a/frontend/src/app/hub/component/hub-search-result/hub-search-result.component.ts +++ b/frontend/src/app/hub/component/hub-search-result/hub-search-result.component.ts @@ -19,8 +19,16 @@ import { AfterViewInit, Component, Input, OnInit, ViewChild } from "@angular/core"; import { Router } from "@angular/router"; -import { SearchResultsComponent } from "../../../dashboard/component/user/search-results/search-results.component"; +import { NgIf } from "@angular/common"; +import { NzButtonComponent } from "ng-zorro-antd/button"; +import { NzIconDirective } from "ng-zorro-antd/icon"; +import { NzTooltipModule } from "ng-zorro-antd/tooltip"; +import { + SearchResultsComponent, + SearchResultsViewMode, +} from "../../../dashboard/component/user/search-results/search-results.component"; import { FiltersComponent } from "../../../dashboard/component/user/filters/filters.component"; +import { DatasetCardItemComponent } from "../../../dashboard/component/user/dataset-card-item/dataset-card-item.component"; import { UntilDestroy, untilDestroyed } from "@ngneat/until-destroy"; import { SortMethod } from "../../../dashboard/type/sort-method"; import { UserService } from "../../../common/service/user/user.service"; @@ -30,17 +38,36 @@ import { firstValueFrom } from "rxjs"; import { map } from "rxjs/operators"; import { SortButtonComponent } from "../../../dashboard/component/user/sort-button/sort-button.component"; +const HUB_DATASET_VIEW_MODE_STORAGE_KEY = "texera.hub.dataset.viewMode"; + @UntilDestroy() @Component({ selector: "texera-hub-search", templateUrl: "./hub-search-result.component.html", styleUrls: ["./hub-search-result.component.scss"], - imports: [SortButtonComponent, FiltersComponent, SearchResultsComponent], + imports: [ + NgIf, + NzButtonComponent, + NzIconDirective, + NzTooltipModule, + SortButtonComponent, + FiltersComponent, + SearchResultsComponent, + DatasetCardItemComponent, + ], }) export class HubSearchResultComponent implements OnInit, AfterViewInit { public searchType: "dataset" | "workflow" = "workflow"; public searchKeywords: string[] = []; currentUid = this.userService.getCurrentUser()?.uid; + public viewMode: SearchResultsViewMode = + localStorage.getItem(HUB_DATASET_VIEW_MODE_STORAGE_KEY) === "card" ? "card" : "list"; + + setViewMode(mode: SearchResultsViewMode): void { + if (this.viewMode === mode) return; + this.viewMode = mode; + localStorage.setItem(HUB_DATASET_VIEW_MODE_STORAGE_KEY, mode); + } private isLogin = false; private includePublic = true; diff --git a/frontend/src/app/hub/service/hub.service.ts b/frontend/src/app/hub/service/hub.service.ts index 66cd08a914..4562ae9c8c 100644 --- a/frontend/src/app/hub/service/hub.service.ts +++ b/frontend/src/app/hub/service/hub.service.ts @@ -20,6 +20,7 @@ import { HttpClient, HttpHeaders, HttpParams } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { Observable } from "rxjs"; +import { map, switchMap } from "rxjs/operators"; import { AppSettings } from "../../common/app-setting"; import { SearchResultItem } from "../../dashboard/type/search-result"; @@ -102,6 +103,26 @@ export class HubService { }); } + /** Like/unlike, then re-fetch the count. */ + public toggleLike( + entityId: number, + entityType: EntityType, + currentlyLiked: boolean + ): Observable<{ liked: boolean; likeCount: number }> { + const action$ = currentlyLiked ? this.postUnlike(entityId, entityType) : this.postLike(entityId, entityType); + return action$.pipe( + switchMap(success => + this.getCounts([entityType], [entityId], [ActionType.Like]).pipe( + map(counts => { + const likeCount = counts[0]?.counts.like ?? 0; + const liked = success ? !currentlyLiked : currentlyLiked; + return { liked, likeCount }; + }) + ) + ) + ); + } + public postView(entityId: number, userId: number, entityType: EntityType): Observable<number> { const body = { entityId, userId, entityType }; return this.http.post<number>(`${this.BASE_URL}/view`, body, {
