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-9063-cc1f201596936a12e79f6243cdc38bef3f73c767 in repository https://gitbox.apache.org/repos/asf/texera.git
commit 448deadba420875cdf825a68cbe816bf3aa15c7b Author: Kary Zheng <[email protected]> AuthorDate: Thu Nov 12 07:18:29 2026 +0000 feat(frontend): pin an operator's result beside it, with a tab per output port (#9063) ### What changes were proposed in this PR? The hover card gets a Pin button. Pinning turns it into a window beside the operator with the whole result table, tied to the operator by a dashed line. Several windows can be open at once; each can be dragged and resized, and follows its operator when it or the canvas moves. An operator with more than one output gets a tab per output port in its window. The first port is the one the running execution reports on. Another port is read when its tab is shown, through the port-aware result service from #9054, and pages by the row count its replies carry. The execution reports a change only for the first port, so another port is read again as results arrive, at most once a second, and once more when the operator completes. If the chosen output is removed, the window shows the last one that is left. The table in a window fills the window: it measures the space its search bar, header, statistics row and pager take, and fits as many rows as are left. It shows its statistics row only when a column has statistics, which another port never has. <img width="1316" height="907" alt="pr3-2-pinned-output-1" src="https://github.com/user-attachments/assets/788964bb-14bd-4a35-853d-6e2743ab0ae9" /> <img width="1447" height="840" alt="pr3-3-pinned-output-2" src="https://github.com/user-attachments/assets/e6495a79-c117-488c-8434-41da58e42914" /> ### Any related issues, documentation, discussions? Closes #9062. Part of #9052. Design discussed in #8842. ### How was this PR tested? A new spec for the pinned window covers its port tabs, the port it shows and the height it hands the table. New cases in the result table's spec cover filling a given height, the statistics row, and refreshing a port past the first. New cases in the editor's spec cover pinning, unpinning, unpinning a deleted operator's window, the window's position as the canvas moves, and the connector line on each side. The affected frontend specs pass. In the running app, a Split of 20 rows into 13 and 7 shows the first output's 13 rows in its first tab and the other 7 in its second, each paged correctly, and the pager ends near the window's bottom edge at any window size. A window pinned on a Split's second output during a run shows its rows when the run ends, and shows the new rows after a re-run. ### Was this PR authored or co-authored using generative AI tooling? Generated-by: Claude Code (Claude Opus 5.5) 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]> --- .../result-panel-modal.component.spec.ts | 9 ++ .../result-table-frame.component.html | 7 +- .../result-table-frame.component.spec.ts | 150 ++++++++++++++++-- .../result-table-frame.component.ts | 85 +++++++++- .../operator-result-preview.component.html | 12 ++ .../operator-result-preview.component.ts | 18 ++- .../pinned-result-window.component.html | 71 +++++++++ .../pinned-result-window.component.scss | 75 +++++++++ .../pinned-result-window.component.spec.ts | 161 +++++++++++++++++++ .../pinned-result-window.component.ts | 146 +++++++++++++++++ .../workflow-editor/workflow-editor.component.html | 19 +++ .../workflow-editor/workflow-editor.component.scss | 24 +++ .../workflow-editor.component.spec.ts | 172 ++++++++++++++++++++- .../workflow-editor/workflow-editor.component.ts | 111 ++++++++++++- frontend/src/jsdom-svg-polyfill.ts | 7 + 15 files changed, 1036 insertions(+), 31 deletions(-) diff --git a/frontend/src/app/workspace/component/result-panel/result-panel-modal.component.spec.ts b/frontend/src/app/workspace/component/result-panel/result-panel-modal.component.spec.ts index e0ccc6f08c..9619595f25 100644 --- a/frontend/src/app/workspace/component/result-panel/result-panel-modal.component.spec.ts +++ b/frontend/src/app/workspace/component/result-panel/result-panel-modal.component.spec.ts @@ -44,7 +44,11 @@ describe("RowModalComponent", () => { pageSize: 10, }; + // the clipboard tests replace navigator.clipboard, and specs share the page within a worker + let originalClipboard: PropertyDescriptor | undefined; + beforeEach(async () => { + originalClipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard"); await TestBed.configureTestingModule({ imports: [RowModalComponent, HttpClientTestingModule], providers: [ @@ -59,6 +63,11 @@ describe("RowModalComponent", () => { }); afterEach(() => { + if (originalClipboard) { + Object.defineProperty(navigator, "clipboard", originalClipboard); + } else { + delete (navigator as any).clipboard; + } httpMock.verify(); }); diff --git a/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.html b/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.html index aadb1775a7..fc5dd05f09 100644 --- a/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.html +++ b/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.html @@ -86,7 +86,7 @@ </th> </tr> <tr - *ngIf="tableStats && prevTableStats" + *ngIf="hasTableStats" #statsRow class="custom-stats-row"> <th *ngFor="let column of currentColumns"> @@ -195,9 +195,10 @@ </span> <!-- Not rendered when result export is switched off for the deployment: every action behind it returns without sending a request, so the button would be there and do - nothing. The top menu and the context menu already honour the same switch. --> + nothing. The top menu and the context menu already honour the same switch. + Nor on a port past the first: a cell export reads the operator's first port. --> <button - *ngIf="guiConfigService.env.exportExecutionResultEnabled" + *ngIf="guiConfigService.env.exportExecutionResultEnabled && portIndex === 0" (click)="downloadData(currentResult[i][column.columnDef], i, columnIndex, column.columnDef); $event.stopPropagation()" nz-button nzType="link" diff --git a/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.spec.ts b/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.spec.ts index 2370a6d1e2..4014739801 100644 --- a/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.spec.ts +++ b/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.spec.ts @@ -19,8 +19,9 @@ import { ComponentFixture, TestBed } from "@angular/core/testing"; import { SimpleChange } from "@angular/core"; +import type { Mock } from "vitest"; -import { ResultTableFrameComponent } from "./result-table-frame.component"; +import { OTHER_PORT_REFRESH_MS, ResultTableFrameComponent } from "./result-table-frame.component"; import { OperatorMetadataService } from "../../../service/operator-metadata/operator-metadata.service"; import { StubOperatorMetadataService } from "../../../service/operator-metadata/stub-operator-metadata.service"; import { HttpClientTestingModule } from "@angular/common/http/testing"; @@ -410,6 +411,38 @@ describe("ResultTableFrameComponent", () => { stateStream.next({ otherOp: OperatorState.Completed }); expect(component.isOperatorFinished).toBe(false); }); + + it("asks once more for a port past the first when the operator completes, as no update may follow", () => { + const stateStream = new Subject<Record<string, OperatorState>>(); + vi.spyOn(workflowStatusService, "getStateUpdateStream").mockReturnValue(stateStream.asObservable()); + const secondPort = { + getCurrentTotalNumTuples: vi.fn().mockReturnValue(6), + selectPage: vi.fn().mockReturnValue(of(makePageEvent(1))), + }; + vi.spyOn(workflowResultService, "getPortPaginatedResultService").mockReturnValue( + secondPort as unknown as OperatorPaginationResultService + ); + recreateComponent("op1"); + component.portIndex = 1; + + stateStream.next({ op1: OperatorState.Running }); + stateStream.next({ op1: OperatorState.Completed }); + stateStream.next({ op1: OperatorState.Completed }); + + expect(secondPort.selectPage).toHaveBeenCalledTimes(1); + expect(component.totalNumTuples).toBe(6); + }); + + it("leaves the first port to its updates when the operator completes", () => { + const stateStream = new Subject<Record<string, OperatorState>>(); + vi.spyOn(workflowStatusService, "getStateUpdateStream").mockReturnValue(stateStream.asObservable()); + const paginated = makePaginatedResultService(); + recreateComponent("op1"); + + stateStream.next({ op1: OperatorState.Completed }); + + expect(paginated.selectPage).not.toHaveBeenCalled(); + }); }); describe("result update stream", () => { @@ -462,16 +495,53 @@ describe("ResultTableFrameComponent", () => { expect(component.totalNumTuples).toBe(0); }); - it("leaves a port past the first alone, as the updates are about the first port", () => { - const paginated = makePaginatedResultService(); - recreateComponent("op1"); - component.portIndex = 1; - component.totalNumTuples = 5; + describe("on a port past the first", () => { + let secondPort: { getCurrentTotalNumTuples: Mock; selectPage: Mock }; - resultUpdates.next({ op1: paginationUpdate(63, [1]) }); + beforeEach(() => { + vi.useFakeTimers(); + secondPort = { + getCurrentTotalNumTuples: vi.fn().mockReturnValue(5), + selectPage: vi.fn().mockReturnValue(of(makePageEvent(1))), + }; + vi.spyOn(workflowResultService, "getPortPaginatedResultService").mockReturnValue( + secondPort as unknown as OperatorPaginationResultService + ); + recreateComponent("op1"); + component.portIndex = 1; + }); - expect(component.totalNumTuples).toBe(5); - expect(paginated.selectPage).not.toHaveBeenCalled(); + afterEach(() => vi.useRealTimers()); + + it("asks for its page again on its operator's update, as the update counts the first port only", () => { + component.totalNumTuples = 3; + + resultUpdates.next({ op1: paginationUpdate(63, [4]) }); + + expect(secondPort.selectPage).toHaveBeenCalledTimes(1); + // the count is the port's own, from the reply, not the first port's + expect(component.totalNumTuples).toBe(5); + }); + + it("ignores another operator's update", () => { + resultUpdates.next({ otherOp: paginationUpdate(9, [1]) }); + vi.advanceTimersByTime(OTHER_PORT_REFRESH_MS); + + expect(secondPort.selectPage).not.toHaveBeenCalled(); + }); + + it("asks at most once a second while a run updates, and always for the last update", () => { + resultUpdates.next({ op1: paginationUpdate(1, [1]) }); + resultUpdates.next({ op1: paginationUpdate(2, [1]) }); + resultUpdates.next({ op1: paginationUpdate(3, [1]) }); + expect(secondPort.selectPage).toHaveBeenCalledTimes(1); + + vi.advanceTimersByTime(OTHER_PORT_REFRESH_MS); + expect(secondPort.selectPage).toHaveBeenCalledTimes(2); + + vi.advanceTimersByTime(OTHER_PORT_REFRESH_MS); + expect(secondPort.selectPage).toHaveBeenCalledTimes(2); + }); }); it("ignores updates when the frame has no operator", () => { @@ -664,6 +734,48 @@ describe("ResultTableFrameComponent", () => { expect(component.pageSize).toBe(1); expect(component.currentPageIndex).toBe(3); }); + + // A table in a pinned window fills that window instead of the result panel. + it("falls back to the panel's rule for the height it is given while no row is drawn", () => { + component.totalNumTuples = 30; + const paginated = makePaginatedResultService(); + component.operatorId = "op1"; + component.containerHeight = 700; + + component.ngOnChanges({ containerHeight: new SimpleChange(undefined, 700, false) }); + + // the same 700 the result panel was given above, so the same 11 rows + expect(component.pageSize).toBe(11); + // a new height alone resizes the page; the table asks for the rows itself, as on a panel resize + expect(paginated.selectPage).not.toHaveBeenCalled(); + + resizeService.changePanelSize(800, 300); + expect(component.pageSize).toBe(11); + }); + + it("fits as many rows as the height leaves under what it measures around the drawn rows", () => { + component.totalNumTuples = 30; + component.operatorId = "op1"; + // the server pages the rows, so both rows given are drawn + component.isFrontPagination = false; + component.setupResultTable([SAMPLE_ROW, { _id: 1, name: "bob", score: 75 }], 30); + fixture.detectChanges(); + const host = fixture.nativeElement as HTMLElement; + const rows = Array.from(host.querySelectorAll<HTMLElement>("tbody tr.ant-table-row")); + expect(rows.length).toBe(2); + // the drawn table is 200px tall, its two rows 40px each, so 120px sit around the rows + const setHeight = (element: HTMLElement, height: number) => + Object.defineProperty(element, "offsetHeight", { configurable: true, get: () => height }); + setHeight(host.querySelector<HTMLElement>(".result-table")!, 200); + rows.forEach(row => setHeight(row, 40)); + component.containerHeight = 450; + + component.ngOnChanges({ containerHeight: new SimpleChange(undefined, 450, false) }); + + // (450 - 120) / 40 rounds down to 8 rows, where the panel's rule would give 4 + expect(component.pageSize).toBe(8); + expect(resizeService.pageSize).toBe(8); + }); }); describe("onTableQueryParamsChange", () => { @@ -866,6 +978,20 @@ describe("ResultTableFrameComponent", () => { expect(fixture.nativeElement.querySelector(".result-table").hidden).toBe(true); }); + // Statistics come only with the first output port, and only once they arrive; an empty row of + // them would be a grey bar with nothing in it. + it("renders no statistics row while no column has statistics", () => { + component.operatorId = "op1"; + component.setupResultTable([SAMPLE_ROW], 1); + component.isFrontPagination = false; + component.tableStats = {}; + component.prevTableStats = {}; + fixture.detectChanges(); + + expect(fixture.nativeElement.querySelector(".result-table").hidden).toBe(false); + expect(fixture.nativeElement.querySelector(".custom-stats-row")).toBeNull(); + }); + it("renders headers, per-column stats, and clickable row cells once results arrive", () => { // The download click below needs a rendered button, and the button is gated on the switch. setExport(true); @@ -939,6 +1065,12 @@ describe("ResultTableFrameComponent", () => { renderOneRow(false); expect(fixture.debugElement.query(By.css("button.download-button"))).toBeNull(); }); + + it("is not rendered on a port past the first, as a cell export reads the first port", () => { + component.portIndex = 1; + renderOneRow(true); + expect(fixture.debugElement.query(By.css("button.download-button"))).toBeNull(); + }); }); }); diff --git a/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.ts b/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.ts index 78d07d8dfd..75ff2d6acf 100644 --- a/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.ts +++ b/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.ts @@ -17,7 +17,7 @@ * under the License. */ -import { ChangeDetectorRef, Component, Input, OnChanges, OnInit, SimpleChanges } from "@angular/core"; +import { ChangeDetectorRef, Component, ElementRef, Input, OnChanges, OnInit, SimpleChanges } from "@angular/core"; import { NzModalRef, NzModalService } from "ng-zorro-antd/modal"; import { NzTableQueryParams, @@ -42,6 +42,7 @@ import { RowModalComponent } from "../result-panel-modal.component"; import { UntilDestroy, untilDestroyed } from "@ngneat/until-destroy"; import { DomSanitizer, SafeHtml } from "@angular/platform-browser"; import { isAudioUrl, isVideoUrl, isImageUrl } from "../../../../common/util/media-type.util"; +import { isDefined } from "../../../../common/util/predicate"; import { ResultExportationComponent } from "../../result-exportation/result-exportation.component"; import { WorkflowStatusService } from "../../../service/workflow-status/workflow-status.service"; import { GuiConfigService } from "../../../../common/service/gui-config.service"; @@ -52,6 +53,10 @@ import { NzButtonComponent } from "ng-zorro-antd/button"; import { NzWaveDirective } from "ng-zorro-antd/core/wave"; import { ɵNzTransitionPatchDirective } from "ng-zorro-antd/core/transition-patch"; import { NzIconDirective } from "ng-zorro-antd/icon"; +import { asyncScheduler, filter, throttleTime } from "rxjs"; + +// how often, at most, a table on a port past the first asks for its page again while a run updates +export const OTHER_PORT_REFRESH_MS = 1000; export type MediaCellType = "video" | "audio" | "image" | "text"; @@ -95,6 +100,9 @@ export class ResultTableFrameComponent implements OnInit, OnChanges { // which of the operator's output ports to show. The running execution reports only on the first, // so another port is read when shown, and its counts and statistics are not followed live. @Input() portIndex = 0; + // The height the table has to fill in a window of its own. Left out, the table fills the result + // panel and follows its height. + @Input() containerHeight?: number; // display result table currentColumns?: TableColumn[]; @@ -119,6 +127,14 @@ export class ResultTableFrameComponent implements OnInit, OnChanges { panelHeight = 0; tableStats: Record<string, Record<string, number>> = {}; prevTableStats: Record<string, Record<string, number>> = {}; + + /** + * Whether any column has statistics to show. Until they arrive there are none, and an output + * port past the first never has any, as the statistics are the first port's. + */ + get hasTableStats(): boolean { + return Object.keys(this.tableStats).length > 0; + } widthPercent: string = ""; isOperatorFinished: boolean = false; @@ -135,6 +151,7 @@ export class ResultTableFrameComponent implements OnInit, OnChanges { private workflowResultService: WorkflowResultService, private resizeService: PanelResizeService, private changeDetectorRef: ChangeDetectorRef, + private elementRef: ElementRef, private sanitizer: DomSanitizer, private workflowStatusService: WorkflowStatusService, // Read by the template only (the export button's flag); the template can see a protected member. @@ -142,7 +159,10 @@ export class ResultTableFrameComponent implements OnInit, OnChanges { ) {} ngOnChanges(changes: SimpleChanges): void { + if (isDefined(this.containerHeight)) this.fitPageSizeToContainer(this.containerHeight); if (changes.operatorId) this.operatorId = changes.operatorId.currentValue; + // A new height alone only resizes the page, as dragging the result panel's edge does. + if (Object.keys(changes).every(key => key === "containerHeight")) return; // another port's rows are not this port's, so a new port starts from an empty table if (changes.portIndex && !changes.portIndex.firstChange) { this.currentResult = []; @@ -174,6 +194,9 @@ export class ResultTableFrameComponent implements OnInit, OnChanges { .pipe(untilDestroyed(this)) .subscribe(stateMap => { if (this.operatorId && stateMap[this.operatorId] === OperatorState.Completed) { + // Another port can still be filling after the first port's last update, so its table + // asks once more when the operator completes. + if (!this.isOperatorFinished && this.portIndex !== 0) this.changePaginatedResultData(); this.isOperatorFinished = true; this.changeDetectorRef.detectChanges(); } else { @@ -205,6 +228,17 @@ export class ResultTableFrameComponent implements OnInit, OnChanges { this.changeDetectorRef.detectChanges(); }); + // Another port has no update of its own, so its table asks for its page again on the + // operator's updates, at most once a second; the last one is always asked for. + this.workflowResultService + .getResultUpdateStream() + .pipe( + filter(update => isDefined(this.operatorId) && this.portIndex !== 0 && isDefined(update[this.operatorId])), + throttleTime(OTHER_PORT_REFRESH_MS, asyncScheduler, { leading: true, trailing: true }), + untilDestroyed(this) + ) + .subscribe(() => this.changePaginatedResultData()); + this.workflowResultService .getResultTableStats() .pipe(untilDestroyed(this)) @@ -225,12 +259,9 @@ export class ResultTableFrameComponent implements OnInit, OnChanges { }); this.resizeService.currentSize.pipe(untilDestroyed(this)).subscribe(size => { - this.panelHeight = size.height; - this.adjustPageSizeBasedOnPanelSize(size.height); - let currentPageNum: number = Math.ceil(this.totalNumTuples / this.pageSize); - while (this.currentPageIndex > currentPageNum && this.currentPageIndex > 1) { - this.currentPageIndex -= 1; - } + // a table given its own height to fill does not follow the result panel's + if (isDefined(this.containerHeight)) return; + this.fitPageSize(size.height); }); if (this.operatorId) { @@ -326,8 +357,10 @@ export class ResultTableFrameComponent implements OnInit, OnChanges { PAGINATION_HEIGHT + SEARCH_BAR_HEIGHT_WITH_MARGIN; - const newPageSize = Math.max(1, Math.floor((panelHeight - usedHeight) / ROW_HEIGHT)); + this.setPageSize(Math.max(1, Math.floor((panelHeight - usedHeight) / ROW_HEIGHT))); + } + private setPageSize(newPageSize: number): void { const oldOffset = (this.currentPageIndex - 1) * this.pageSize; this.pageSize = newPageSize; @@ -336,6 +369,40 @@ export class ResultTableFrameComponent implements OnInit, OnChanges { this.currentPageIndex = Math.floor(oldOffset / newPageSize) + 1; } + /** As many rows to a page as fill the result panel, keeping the page within the result. */ + private fitPageSize(height: number): void { + this.panelHeight = height; + this.adjustPageSizeBasedOnPanelSize(height); + this.keepPageWithinResult(); + } + + /** + * In a window of its own, the table measures what it draws around its rows, the search bar, + * header, statistics and pager, so its rows take up the rest. Until a row is drawn there is + * nothing to measure, and the panel's rule stands in. + */ + private fitPageSizeToContainer(height: number): void { + const table = (this.elementRef.nativeElement as HTMLElement).querySelector<HTMLElement>(".result-table"); + const rows = Array.from(table?.querySelectorAll<HTMLElement>("tbody tr.ant-table-row") ?? []); + const rowsHeight = rows.reduce((sum, row) => sum + row.offsetHeight, 0); + if (!table || rowsHeight === 0) { + this.fitPageSize(height); + return; + } + const aroundRows = table.offsetHeight - rowsHeight; + const pageSize = Math.max(1, Math.floor((height - aroundRows) / (rowsHeight / rows.length))); + if (pageSize === this.pageSize) return; + this.setPageSize(pageSize); + this.keepPageWithinResult(); + } + + private keepPageWithinResult(): void { + let currentPageNum: number = Math.ceil(this.totalNumTuples / this.pageSize); + while (this.currentPageIndex > currentPageNum && this.currentPageIndex > 1) { + this.currentPageIndex -= 1; + } + } + /** * Callback function for table query params changed event * params containing new page index, new page size, and more @@ -437,6 +504,8 @@ export class ResultTableFrameComponent implements OnInit, OnChanges { } this.setupResultTable(pageData.table, paginatedResultService.getCurrentTotalNumTuples(), pageData.schema); this.changeDetectorRef.detectChanges(); + // the rows are drawn now, so a table in a window can measure what fits + if (isDefined(this.containerHeight)) this.fitPageSizeToContainer(this.containerHeight); }); } diff --git a/frontend/src/app/workspace/component/workflow-editor/operator-result-preview/operator-result-preview.component.html b/frontend/src/app/workspace/component/workflow-editor/operator-result-preview/operator-result-preview.component.html index d6b6cd1d9b..c9753fbaf5 100644 --- a/frontend/src/app/workspace/component/workflow-editor/operator-result-preview/operator-result-preview.component.html +++ b/frontend/src/app/workspace/component/workflow-editor/operator-result-preview/operator-result-preview.component.html @@ -27,6 +27,18 @@ [class.result-preview__summary--error]="preview.kind === 'error'" >{{ preview.summary }}</span > + <button + *ngIf="pinnable" + nz-button + nzSize="small" + type="button" + title="Pin the result next to the operator" + (click)="pin.emit()"> + <span + nz-icon + nzType="pushpin"></span> + Pin + </button> </div> <table *ngIf="preview.columns.length > 0" diff --git a/frontend/src/app/workspace/component/workflow-editor/operator-result-preview/operator-result-preview.component.ts b/frontend/src/app/workspace/component/workflow-editor/operator-result-preview/operator-result-preview.component.ts index 159725f1ea..da2b6d59b4 100644 --- a/frontend/src/app/workspace/component/workflow-editor/operator-result-preview/operator-result-preview.component.ts +++ b/frontend/src/app/workspace/component/workflow-editor/operator-result-preview/operator-result-preview.component.ts @@ -17,8 +17,19 @@ * under the License. */ -import { ChangeDetectorRef, Component, Input, OnChanges, OnInit, SimpleChanges } from "@angular/core"; +import { + ChangeDetectorRef, + Component, + EventEmitter, + Input, + OnChanges, + OnInit, + Output, + SimpleChanges, +} from "@angular/core"; import { NgFor, NgIf } from "@angular/common"; +import { NzButtonComponent } from "ng-zorro-antd/button"; +import { NzIconDirective } from "ng-zorro-antd/icon"; import { Subscription } from "rxjs"; import { filter } from "rxjs/operators"; import { UntilDestroy, untilDestroyed } from "@ngneat/until-destroy"; @@ -62,10 +73,13 @@ export interface OperatorResultPreview { selector: "texera-operator-result-preview", templateUrl: "./operator-result-preview.component.html", styleUrls: ["./operator-result-preview.component.scss"], - imports: [NgIf, NgFor], + imports: [NgIf, NgFor, NzButtonComponent, NzIconDirective], }) export class OperatorResultPreviewComponent implements OnInit, OnChanges { @Input() operatorId = ""; + // whether the card offers to pin the result next to the operator + @Input() pinnable = false; + @Output() pin = new EventEmitter<void>(); // The first rows of a table result, one string per shown column; undefined while they load. rows: readonly (readonly string[])[] | undefined = undefined; diff --git a/frontend/src/app/workspace/component/workflow-editor/pinned-result-window/pinned-result-window.component.html b/frontend/src/app/workspace/component/workflow-editor/pinned-result-window/pinned-result-window.component.html new file mode 100644 index 0000000000..00b587d3f7 --- /dev/null +++ b/frontend/src/app/workspace/component/workflow-editor/pinned-result-window/pinned-result-window.component.html @@ -0,0 +1,71 @@ +<!-- + 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. +--> + +<div class="pinned-result"> + <div + class="pinned-result__header" + (mousedown)="startDrag($event)"> + <span + nz-icon + nzType="pushpin" + nzTheme="fill"></span> + <span class="pinned-result__title">{{ title }}</span> + <button + nz-button + nzType="text" + nzSize="small" + type="button" + [attr.aria-label]="'Unpin ' + title" + (click)="closed.emit()"> + <span + nz-icon + nzType="close"></span> + </button> + </div> + <div + *ngIf="kind === 'table' && outputPorts.length > 1" + class="pinned-result__ports" + role="tablist"> + <button + *ngFor="let port of outputPorts; trackBy: trackPort" + type="button" + role="tab" + class="pinned-result__port" + [class.pinned-result__port--active]="port.index === shownPort" + [attr.aria-selected]="port.index === shownPort" + (click)="selectedPort = port.index"> + {{ port.label }} + </button> + </div> + <div + #body + class="pinned-result__body"> + <texera-result-table-frame + *ngIf="kind === 'table'" + [operatorId]="operatorId" + [portIndex]="shownPort" + [containerHeight]="tableHeight"></texera-result-table-frame> + <texera-visualization-panel-content + *ngIf="kind === 'chart'" + [operatorId]="operatorId"></texera-visualization-panel-content> + <texera-operator-result-preview + *ngIf="kind === 'other'" + [operatorId]="operatorId"></texera-operator-result-preview> + </div> +</div> diff --git a/frontend/src/app/workspace/component/workflow-editor/pinned-result-window/pinned-result-window.component.scss b/frontend/src/app/workspace/component/workflow-editor/pinned-result-window/pinned-result-window.component.scss new file mode 100644 index 0000000000..68bc2a1b40 --- /dev/null +++ b/frontend/src/app/workspace/component/workflow-editor/pinned-result-window/pinned-result-window.component.scss @@ -0,0 +1,75 @@ +/** + * 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. + */ + +.pinned-result { + width: 520px; + // tall enough for the table's first page to hold 5 rows, as the result panel's does + height: 480px; + min-width: 280px; + min-height: 160px; + display: flex; + flex-direction: column; + // the bottom-right corner resizes the window + resize: both; + overflow: hidden; + background: white; + border: 1px solid #d9d9d9; + border-radius: 6px; + + &__header { + display: flex; + align-items: center; + gap: 6px; + padding: 2px 2px 2px 10px; + cursor: move; + background: #fafafa; + } + + &__title { + flex: 1; + font-weight: 600; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + &__ports { + display: flex; + overflow-x: auto; + } + + &__port { + padding: 4px 10px; + border: none; + border-bottom: 2px solid transparent; + background: transparent; + cursor: pointer; + + &--active { + border-bottom-color: #1890ff; + color: #1890ff; + } + } + + &__body { + flex: 1; + min-height: 0; + overflow: auto; + } +} diff --git a/frontend/src/app/workspace/component/workflow-editor/pinned-result-window/pinned-result-window.component.spec.ts b/frontend/src/app/workspace/component/workflow-editor/pinned-result-window/pinned-result-window.component.spec.ts new file mode 100644 index 0000000000..120193b082 --- /dev/null +++ b/frontend/src/app/workspace/component/workflow-editor/pinned-result-window/pinned-result-window.component.spec.ts @@ -0,0 +1,161 @@ +/** + * 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 { Component, Input } from "@angular/core"; +import { ComponentFixture, TestBed } from "@angular/core/testing"; +import { By } from "@angular/platform-browser"; +import { PinnedResultWindowComponent } from "./pinned-result-window.component"; +import { ResultTableFrameComponent } from "../../result-panel/result-table-frame/result-table-frame.component"; +import { VisualizationFrameContentComponent } from "../../visualization-panel-content/visualization-frame-content.component"; +import { OperatorResultPreviewComponent } from "../operator-result-preview/operator-result-preview.component"; +import { WorkflowActionService } from "../../../service/workflow-graph/model/workflow-action.service"; +import { + OperatorPaginationResultService, + WorkflowResultService, +} from "../../../service/workflow-result/workflow-result.service"; +import { OperatorPredicate, PortDescription } from "../../../types/workflow-common.interface"; + +// Stand-ins for the frames the window holds, so the test needs none of their services. +@Component({ selector: "texera-result-table-frame", template: "", standalone: true }) +class StubTableFrame { + @Input() operatorId?: string; + @Input() portIndex = 0; + @Input() containerHeight?: number; +} + +@Component({ selector: "texera-visualization-panel-content", template: "", standalone: true }) +class StubChartFrame { + @Input() operatorId?: string; +} + +@Component({ selector: "texera-operator-result-preview", template: "", standalone: true }) +class StubPreview { + @Input() operatorId?: string; +} + +describe("PinnedResultWindowComponent", () => { + let fixture: ComponentFixture<PinnedResultWindowComponent>; + let operator: OperatorPredicate; + let hasTable: boolean; + + const ports = (...names: (string | undefined)[]): PortDescription[] => + names.map((displayName, i) => ({ portID: `output-${i}`, displayName })); + + beforeEach(async () => { + operator = { operatorID: "op1", operatorType: "Split", outputPorts: ports(undefined) } as OperatorPredicate; + hasTable = true; + const graph = { hasOperator: () => true, getOperator: () => operator }; + + await TestBed.configureTestingModule({ + imports: [PinnedResultWindowComponent], + providers: [ + { provide: WorkflowActionService, useValue: { getTexeraGraph: () => graph } }, + { + provide: WorkflowResultService, + useValue: { + getPaginatedResultService: () => (hasTable ? ({} as OperatorPaginationResultService) : undefined), + getResultService: () => undefined, + }, + }, + ], + }) + .overrideComponent(PinnedResultWindowComponent, { + remove: { + imports: [ResultTableFrameComponent, VisualizationFrameContentComponent, OperatorResultPreviewComponent], + }, + add: { imports: [StubTableFrame, StubChartFrame, StubPreview] }, + }) + .compileComponents(); + + fixture = TestBed.createComponent(PinnedResultWindowComponent); + fixture.componentRef.setInput("operatorId", "op1"); + }); + + const tabs = () => fixture.debugElement.queryAll(By.css(".pinned-result__port")); + const table = () => fixture.debugElement.query(By.directive(StubTableFrame)).componentInstance as StubTableFrame; + + it("shows no port tabs for an operator with one output", () => { + fixture.detectChanges(); + + expect(tabs().length).toBe(0); + expect(table().portIndex).toBe(0); + }); + + it("shows a tab for each output, named as on the canvas or by its place, the first one shown", () => { + operator = { ...operator, outputPorts: ports("False", "True") }; + fixture.detectChanges(); + expect(tabs().map(tab => (tab.nativeElement as HTMLElement).textContent?.trim())).toEqual(["False", "True"]); + + operator = { ...operator, outputPorts: ports(undefined, "") }; + fixture.detectChanges(); + expect(tabs().map(tab => (tab.nativeElement as HTMLElement).textContent?.trim())).toEqual(["Output 1", "Output 2"]); + expect(tabs()[0].classes["pinned-result__port--active"]).toBe(true); + expect(table().portIndex).toBe(0); + }); + + it("shows the output whose tab is clicked", () => { + operator = { ...operator, outputPorts: ports("False", "True") }; + fixture.detectChanges(); + + (tabs()[1].nativeElement as HTMLElement).click(); + fixture.detectChanges(); + + expect(table().portIndex).toBe(1); + expect(table().operatorId).toBe("op1"); + expect(tabs()[1].attributes["aria-selected"]).toBe("true"); + expect(tabs()[0].attributes["aria-selected"]).toBe("false"); + }); + + it("shows the last output when the chosen one is removed, and the chosen one again when it is back", () => { + operator = { ...operator, outputPorts: ports("Out 1", "Out 2", "Out 3") }; + fixture.detectChanges(); + (tabs()[2].nativeElement as HTMLElement).click(); + fixture.detectChanges(); + + operator = { ...operator, outputPorts: ports("Out 1", "Out 2") }; + fixture.detectChanges(); + expect(table().portIndex).toBe(1); + expect(tabs()[1].classes["pinned-result__port--active"]).toBe(true); + + operator = { ...operator, outputPorts: ports("Out 1") }; + fixture.detectChanges(); + expect(tabs().length).toBe(0); + expect(table().portIndex).toBe(0); + + operator = { ...operator, outputPorts: ports("Out 1", "Out 2", "Out 3") }; + fixture.detectChanges(); + expect(table().portIndex).toBe(2); + }); + + it("hands the table the height its body leaves, not the result panel's", () => { + fixture.detectChanges(); + fixture.componentInstance.tableHeight = 400; + fixture.detectChanges(); + + expect(table().containerHeight).toBe(400); + }); + + it("shows no port tabs when the result is not a table", () => { + operator = { ...operator, outputPorts: ports("False", "True") }; + hasTable = false; + fixture.detectChanges(); + + expect(tabs().length).toBe(0); + }); +}); diff --git a/frontend/src/app/workspace/component/workflow-editor/pinned-result-window/pinned-result-window.component.ts b/frontend/src/app/workspace/component/workflow-editor/pinned-result-window/pinned-result-window.component.ts new file mode 100644 index 0000000000..845e39792a --- /dev/null +++ b/frontend/src/app/workspace/component/workflow-editor/pinned-result-window/pinned-result-window.component.ts @@ -0,0 +1,146 @@ +/** + * 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 { + AfterViewInit, + ChangeDetectorRef, + Component, + ElementRef, + EventEmitter, + Input, + OnDestroy, + Output, + ViewChild, +} from "@angular/core"; +import { NgFor, NgIf } from "@angular/common"; +import { NzButtonComponent } from "ng-zorro-antd/button"; +import { NzIconDirective } from "ng-zorro-antd/icon"; +import { WorkflowActionService } from "../../../service/workflow-graph/model/workflow-action.service"; +import { WorkflowResultService } from "../../../service/workflow-result/workflow-result.service"; +import { ResultTableFrameComponent } from "../../result-panel/result-table-frame/result-table-frame.component"; +import { VisualizationFrameContentComponent } from "../../visualization-panel-content/visualization-frame-content.component"; +import { OperatorResultPreviewComponent } from "../operator-result-preview/operator-result-preview.component"; + +/** + * An operator's result pinned next to it on the canvas. It shows the whole result, the way the + * result panel would, and stays until it is closed. Dragging its header moves it away from the + * operator; the editor keeps it at that offset when the operator or the canvas moves. + */ +@Component({ + selector: "texera-pinned-result-window", + templateUrl: "./pinned-result-window.component.html", + styleUrls: ["./pinned-result-window.component.scss"], + imports: [ + NgIf, + NgFor, + NzButtonComponent, + NzIconDirective, + ResultTableFrameComponent, + VisualizationFrameContentComponent, + OperatorResultPreviewComponent, + ], +}) +export class PinnedResultWindowComponent implements AfterViewInit, OnDestroy { + @Input() operatorId = ""; + @Output() closed = new EventEmitter<void>(); + @Output() moved = new EventEmitter<{ dx: number; dy: number }>(); + @ViewChild("body") bodyElement?: ElementRef<HTMLElement>; + + /** The height the window's body leaves for the table, which fills it. */ + tableHeight?: number; + private resizeObserver?: ResizeObserver; + + constructor( + private workflowActionService: WorkflowActionService, + private workflowResultService: WorkflowResultService, + private changeDetectorRef: ChangeDetectorRef + ) {} + + ngAfterViewInit(): void { + const element = this.bodyElement?.nativeElement; + if (!element || typeof ResizeObserver === "undefined") return; + // the user resizes the window by its corner, so the body's height is read as it changes + this.resizeObserver = new ResizeObserver(() => { + const style = getComputedStyle(element); + const height = element.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom); + if (height === this.tableHeight) return; + this.tableHeight = height; + this.changeDetectorRef.detectChanges(); + }); + this.resizeObserver.observe(element); + } + + ngOnDestroy(): void { + this.resizeObserver?.disconnect(); + } + + get title(): string { + const graph = this.workflowActionService.getTexeraGraph(); + if (!graph.hasOperator(this.operatorId)) return this.operatorId; + const operator = graph.getOperator(this.operatorId); + return operator.customDisplayName ?? operator.operatorType; + } + + /** The output port chosen by its tab. */ + selectedPort = 0; + + /** The port shown: the one chosen, or the last when the chosen one is gone. */ + get shownPort(): number { + return Math.min(this.selectedPort, Math.max(this.outputPorts.length - 1, 0)); + } + + /** The operator's output ports, each named as on the canvas, or by its place when unnamed. */ + get outputPorts(): { index: number; label: string }[] { + const graph = this.workflowActionService.getTexeraGraph(); + if (!graph.hasOperator(this.operatorId)) return []; + return graph + .getOperator(this.operatorId) + .outputPorts.map((port, index) => ({ index, label: port.displayName || `Output ${index + 1}` })); + } + + // The list is rebuilt on every check, so a tab is its port's, else each check replaces the tab being clicked. + trackPort(_index: number, port: { index: number }): number { + return port.index; + } + + get kind(): "table" | "chart" | "other" { + if (this.workflowResultService.getPaginatedResultService(this.operatorId)) return "table"; + if (this.workflowResultService.getResultService(this.operatorId)) return "chart"; + return "other"; + } + + /** Drag by the header. Reports how far the pointer moved, so the editor can keep the offset. */ + startDrag(event: MouseEvent): void { + if ((event.target as HTMLElement).closest("button")) return; + event.preventDefault(); + let lastX = event.clientX; + let lastY = event.clientY; + const move = (e: MouseEvent) => { + this.moved.emit({ dx: e.clientX - lastX, dy: e.clientY - lastY }); + lastX = e.clientX; + lastY = e.clientY; + }; + const stop = () => { + window.removeEventListener("mousemove", move); + window.removeEventListener("mouseup", stop); + }; + window.addEventListener("mousemove", move); + window.addEventListener("mouseup", stop); + } +} diff --git a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.html b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.html index 7e777e5f48..fc44127127 100644 --- a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.html +++ b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.html @@ -31,10 +31,29 @@ <div class="heatmap-tooltip__row">{{ heatmapTooltip.metricLabel }}</div> <div class="heatmap-tooltip__row">Heat: {{ heatmapTooltip.heatLabel }}</div> </div> + <svg + *ngIf="pinnedResults.length > 0" + class="pinned-result-connectors"> + <path + *ngFor="let pinned of pinnedResults; trackBy: trackPinnedResult" + class="pinned-result-connector" + [attr.d]="pinnedConnectorPath(pinned)"></path> + </svg> + <texera-pinned-result-window + *ngFor="let pinned of pinnedResults; trackBy: trackPinnedResult" + class="pinned-result-anchor" + [attr.data-operator-id]="pinned.operatorId" + [operatorId]="pinned.operatorId" + [style.left.px]="pinnedResultPosition(pinned).x" + [style.top.px]="pinnedResultPosition(pinned).y" + (moved)="movePinnedResult(pinned.operatorId, $event)" + (closed)="unpinResult(pinned.operatorId)"></texera-pinned-result-window> <texera-operator-result-preview class="result-preview-anchor" *ngIf="resultPreview" [operatorId]="resultPreview.operatorId" + [pinnable]="true" + (pin)="pinResultPreview()" (mouseenter)="keepResultPreview()" (mouseleave)="hideResultPreviewSoon()" [style.left.px]="resultPreview.x" diff --git a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.scss b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.scss index 26812ce4fc..9074d8e036 100644 --- a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.scss +++ b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.scss @@ -39,6 +39,30 @@ z-index: 11; } +.pinned-result-anchor { + position: absolute; + z-index: 10; +} + +// One layer under the windows for the lines that tie each window to its operator. +.pinned-result-connectors { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + z-index: 9; + overflow: visible; + pointer-events: none; +} + +.pinned-result-connector { + fill: none; + stroke: #1890ff; + stroke-width: 1.5; + stroke-dasharray: 5 4; +} + .heatmap-tooltip { position: absolute; z-index: 11; diff --git a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.spec.ts b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.spec.ts index 641c646dac..43fa22c96c 100644 --- a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.spec.ts +++ b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.spec.ts @@ -25,7 +25,13 @@ import { DragDropService } from "../../service/drag-drop/drag-drop.service"; import { WorkflowUtilService } from "../../service/workflow-graph/util/workflow-util.service"; import { ComponentFixture, fakeAsync, TestBed, tick } from "@angular/core/testing"; import { ValidationWorkflowService } from "../../service/validation/validation-workflow.service"; -import { RESULT_PREVIEW_DELAY_MS, RESULT_PREVIEW_HIDE_MS, WorkflowEditorComponent } from "./workflow-editor.component"; +import { + PINNED_HEADER_HEIGHT, + RESULT_PREVIEW_DELAY_MS, + RESULT_PREVIEW_HIDE_MS, + WorkflowEditorComponent, +} from "./workflow-editor.component"; +import { PinnedResultWindowComponent } from "./pinned-result-window/pinned-result-window.component"; import { workflowEditorTestImports, workflowEditorTestProviders } from "./workflow-editor.test-utils"; import { OperatorMetadataService } from "../../service/operator-metadata/operator-metadata.service"; import { StubOperatorMetadataService } from "../../service/operator-metadata/stub-operator-metadata.service"; @@ -472,6 +478,170 @@ describe("WorkflowEditorComponent", () => { expect(component.resultPreview).toBeNull(); })); + describe("pinned result windows", () => { + const pinnedWindows = () => fixture.debugElement.queryAll(By.css("texera-pinned-result-window")); + + /** Open the scan operator's card and pin it, as its Pin button does. */ + function pinScan(): void { + const view = component.paper.findViewByModel(mockScanPredicate.operatorID); + component.paper.trigger("element:mouseenter", view, new MouseEvent("mouseenter")); + tick(RESULT_PREVIEW_DELAY_MS); + component.pinResultPreview(); + fixture.detectChanges(); + } + + /** The scan operator's box as drawn, in the editor's coordinates. */ + function scanBox(): { left: number; right: number; top: number; bottom: number } { + const bbox = component.paper.getModelById(mockScanPredicate.operatorID).getBBox(); + const { sx, sy } = component.paper.scale(); + const { tx, ty } = component.paper.translate(); + return { + left: bbox.x * sx + tx, + right: (bbox.x + bbox.width) * sx + tx, + top: bbox.y * sy + ty, + bottom: (bbox.y + bbox.height) * sy + ty, + }; + } + + it("pins the card's operator as a window and closes the card, which that operator no longer opens", fakeAsync(() => { + addLinkedPair(); + pinScan(); + + expect(component.resultPreview).toBeNull(); + expect(component.pinnedResults).toEqual([{ operatorId: mockScanPredicate.operatorID, dx: 0, dy: 0 }]); + expect(pinnedWindows().length).toBe(1); + expect(pinnedWindows()[0].attributes["data-operator-id"]).toBe(mockScanPredicate.operatorID); + + const view = component.paper.findViewByModel(mockScanPredicate.operatorID); + component.paper.trigger("element:mouseenter", view, new MouseEvent("mouseenter")); + tick(RESULT_PREVIEW_DELAY_MS); + expect(component.resultPreview).toBeNull(); + })); + + it("unpins a window when it is closed", fakeAsync(() => { + addLinkedPair(); + pinScan(); + + (pinnedWindows()[0].componentInstance as PinnedResultWindowComponent).closed.emit(); + fixture.detectChanges(); + + expect(component.pinnedResults).toEqual([]); + expect(pinnedWindows().length).toBe(0); + })); + + it("unpins the window of a deleted operator, but not another's", fakeAsync(() => { + addLinkedPair(); + pinScan(); + const workflowActionService = TestBed.inject(WorkflowActionService); + + workflowActionService.deleteOperator(mockResultPredicate.operatorID); + expect(component.pinnedResults.map(pinned => pinned.operatorId)).toEqual([mockScanPredicate.operatorID]); + + workflowActionService.deleteOperator(mockScanPredicate.operatorID); + expect(component.pinnedResults).toEqual([]); + expect(pinnedWindows().length).toBe(0); + })); + + it("places a window just right of its operator, level with its top, and keeps it there as the canvas moves", fakeAsync(() => { + addLinkedPair(); + pinScan(); + const pinned = component.pinnedResults[0]; + + let box = scanBox(); + expect(component.pinnedResultPosition(pinned)).toEqual({ x: box.right + 12, y: box.top }); + + component.paper.translate(40, -25); + component.paper.scale(0.5, 0.5); + box = scanBox(); + expect(component.pinnedResultPosition(pinned)).toEqual({ x: box.right + 12, y: box.top }); + })); + + it("keeps a dragged window at the offset it was dragged to", fakeAsync(() => { + addLinkedPair(); + pinScan(); + const box = scanBox(); + + component.movePinnedResult(mockScanPredicate.operatorID, { dx: 30, dy: 10 }); + component.movePinnedResult(mockScanPredicate.operatorID, { dx: -5, dy: 15 }); + component.movePinnedResult("another-operator", { dx: 100, dy: 100 }); + + expect(component.pinnedResults[0]).toEqual({ operatorId: mockScanPredicate.operatorID, dx: 25, dy: 25 }); + expect(component.pinnedResultPosition(component.pinnedResults[0])).toEqual({ + x: box.right + 12 + 25, + y: box.top + 25, + }); + })); + + describe("the line from an operator to its window", () => { + const WIDTH = 300; + const HEIGHT = 200; + + // a window's size is read from the page, which lays nothing out in a test + beforeEach(() => + vi.spyOn(component as any, "pinnedWindowSize").mockReturnValue({ width: WIDTH, height: HEIGHT }) + ); + + /** The path's start and end points. */ + function ends(path: string): number[][] { + const numbers = path.match(/-?[\d.]+/g)!.map(Number); + return [numbers.slice(0, 2), numbers.slice(-2)]; + } + + it("runs from the operator's right side into the header of a window on its right", fakeAsync(() => { + addLinkedPair(); + pinScan(); + const box = scanBox(); + const corner = component.pinnedResultPosition(component.pinnedResults[0]); + + expect(ends(component.pinnedConnectorPath(component.pinnedResults[0]))).toEqual([ + [box.right, (box.top + box.bottom) / 2], + [corner.x, corner.y + PINNED_HEADER_HEIGHT / 2], + ]); + })); + + it("runs from the operator's left side into the header of a window dragged to its left", fakeAsync(() => { + addLinkedPair(); + pinScan(); + const box = scanBox(); + component.movePinnedResult(mockScanPredicate.operatorID, { + dx: -(box.right - box.left) - WIDTH - 100, + dy: 0, + }); + const corner = component.pinnedResultPosition(component.pinnedResults[0]); + + expect(ends(component.pinnedConnectorPath(component.pinnedResults[0]))).toEqual([ + [box.left, (box.top + box.bottom) / 2], + [corner.x + WIDTH, corner.y + PINNED_HEADER_HEIGHT / 2], + ]); + })); + + it("runs from the operator's bottom to the top of a window dragged below it, and top to bottom above", fakeAsync(() => { + addLinkedPair(); + pinScan(); + const box = scanBox(); + const midX = (box.left + box.right) / 2; + // under the operator: the window's left edge left of the operator's middle + component.movePinnedResult(mockScanPredicate.operatorID, { dx: -(box.right - box.left), dy: 0 }); + component.movePinnedResult(mockScanPredicate.operatorID, { dx: 0, dy: box.bottom - box.top + 50 }); + let corner = component.pinnedResultPosition(component.pinnedResults[0]); + expect(ends(component.pinnedConnectorPath(component.pinnedResults[0]))).toEqual([ + [midX, box.bottom], + [midX, corner.y], + ]); + + component.movePinnedResult(mockScanPredicate.operatorID, { + dx: 0, + dy: -(box.bottom - box.top + 50) - HEIGHT - 80, + }); + corner = component.pinnedResultPosition(component.pinnedResults[0]); + expect(ends(component.pinnedConnectorPath(component.pinnedResults[0]))).toEqual([ + [midX, box.top], + [midX, corner.y + HEIGHT], + ]); + })); + }); + }); + /** Select the scan operator the way a click does and return its model, whose attrs say what is on show. */ function selectScanOperator(): joint.dia.Cell { addLinkedPair(); diff --git a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts index 023f2624da..90a7027f59 100644 --- a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts +++ b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts @@ -52,10 +52,11 @@ import concaveman from "concaveman"; import { OperatorResultSummary, AgentService } from "../../service/agent/agent.service"; import { NzNoAnimationDirective } from "ng-zorro-antd/core/animation"; import { ContextMenuComponent } from "./context-menu/context-menu/context-menu.component"; -import { NgIf } from "@angular/common"; +import { NgFor, NgIf } from "@angular/common"; import { AgentInteractionComponent } from "../agent/agent-interaction/agent-interaction.component"; import { HeatmapLegendComponent } from "../heatmap-legend/heatmap-legend.component"; import { OperatorResultPreviewComponent } from "./operator-result-preview/operator-result-preview.component"; +import { PinnedResultWindowComponent } from "./pinned-result-window/pinned-result-window.component"; import { JupyterPanelService } from "../../service/jupyter-panel/jupyter-panel.service"; // jointjs interactive options for enabling and disabling interactivity @@ -83,6 +84,8 @@ export const MAIN_CANVAS = { export const RESULT_PREVIEW_DELAY_MS = 500; /** How long the card stays after the pointer leaves, so the pointer can move into it. */ export const RESULT_PREVIEW_HIDE_MS = 200; +/** The height of a pinned window's header, where the line from its operator comes in. */ +export const PINNED_HEADER_HEIGHT = 30; /** Whether a mouse button is down. JointJS hands over a jQuery event, which keeps the DOM one inside. */ function isButtonHeld(evt: unknown): boolean { @@ -116,6 +119,8 @@ function isButtonHeld(evt: unknown): boolean { AgentInteractionComponent, HeatmapLegendComponent, OperatorResultPreviewComponent, + PinnedResultWindowComponent, + NgFor, ], }) export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy { @@ -134,6 +139,8 @@ export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy } | null = null; // The hovered operator's result preview, and where to show it. Null when hidden. public resultPreview: { operatorId: string; x: number; y: number } | null = null; + // Results pinned beside their operators, each with how far it was dragged from its spot. + public pinnedResults: { operatorId: string; dx: number; dy: number }[] = []; private previewShowTimer?: ReturnType<typeof setTimeout>; // The operator previewShowTimer opens the card for. private previewPendingOperatorId?: string; @@ -614,8 +621,9 @@ export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy } /** - * Shows the hovered operator's result preview beside it. Off when Layers > Result preview is - * unchecked, and while the heat-map overlay is on, whose own tooltip answers the hover then. + * Shows the hovered operator's result preview beside it; its Pin button keeps the whole result + * there. Off when Layers > Result preview is unchecked, and while the heat-map overlay is on, + * whose own tooltip answers the hover then. */ private handleResultPreviewHover(): void { fromJointPaperEvent(this.paper, "element:mouseenter") @@ -628,7 +636,11 @@ export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy } const operatorId = elementView.model.id.toString(); // no preview while a button is held: the pointer is dragging an operator or a link - if (!this.workflowActionService.getTexeraGraph().hasOperator(operatorId) || isButtonHeld(evt)) { + if ( + !this.workflowActionService.getTexeraGraph().hasOperator(operatorId) || + isButtonHeld(evt) || + this.pinnedResults.some(pinned => pinned.operatorId === operatorId) + ) { return; } // Only a pointer that rests on the operator opens the card, so passing over one does not. @@ -658,16 +670,27 @@ export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy this.changeDetectorRef.detectChanges(); }); - // A deleted operator takes its card along, and a card still waiting to open for it. + // Pinned windows sit beside their operators, so they move when an operator or the canvas does. + merge( + fromJointPaperEvent(this.paper, "translate"), + fromJointPaperEvent(this.paper, "scale"), + fromEvent(this.paper.model as any, "change:position") + ) + .pipe(untilDestroyed(this)) + .subscribe(() => { + if (this.pinnedResults.length > 0) this.changeDetectorRef.detectChanges(); + }); + + // A deleted operator takes its window and its card along, and a card still waiting to open for it. this.workflowActionService .getTexeraGraph() .getOperatorDeleteStream() .pipe(untilDestroyed(this)) .subscribe(({ deletedOperatorID }) => { if (this.previewPendingOperatorId === deletedOperatorID) clearTimeout(this.previewShowTimer); - if (this.resultPreview?.operatorId !== deletedOperatorID) return; - this.resultPreview = null; - this.changeDetectorRef.detectChanges(); + if (this.resultPreview?.operatorId === deletedOperatorID) this.resultPreview = null; + // detects changes for both + this.unpinResult(deletedOperatorID); }); } @@ -685,6 +708,78 @@ export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy clearTimeout(this.previewHideTimer); } + public pinResultPreview(): void { + if (this.resultPreview === null) return; + this.pinnedResults = [...this.pinnedResults, { operatorId: this.resultPreview.operatorId, dx: 0, dy: 0 }]; + this.resultPreview = null; + } + + public unpinResult(operatorId: string): void { + this.pinnedResults = this.pinnedResults.filter(pinned => pinned.operatorId !== operatorId); + this.changeDetectorRef.detectChanges(); + } + + // A window is its operator's, so a move keeps the window being dragged instead of rebuilding it. + public trackPinnedResult(_index: number, pinned: { operatorId: string }): string { + return pinned.operatorId; + } + + public movePinnedResult(operatorId: string, delta: { dx: number; dy: number }): void { + this.pinnedResults = this.pinnedResults.map(pinned => + pinned.operatorId === operatorId ? { ...pinned, dx: pinned.dx + delta.dx, dy: pinned.dy + delta.dy } : pinned + ); + } + + /** Where a pinned window goes: beside its operator, plus however far it was dragged from there. */ + public pinnedResultPosition(pinned: { operatorId: string; dx: number; dy: number }): { x: number; y: number } { + const anchor = this.operatorAnchor(pinned.operatorId); + return { x: anchor.x + pinned.dx, y: anchor.y + pinned.dy }; + } + + /** + * The line from an operator to its pinned window, a curve like the links between operators. + * Beside the operator, it runs side to side into the window's header; above or below, it runs + * from the operator's top or bottom to the window's nearest edge. + */ + public pinnedConnectorPath(pinned: { operatorId: string; dx: number; dy: number }): string { + const cell = this.paper.getModelById(pinned.operatorId); + if (!cell) return ""; + const bbox = cell.getBBox(); + const scale = this.paper.scale(); + const translate = this.paper.translate(); + const op = { + left: bbox.x * scale.sx + translate.tx, + right: (bbox.x + bbox.width) * scale.sx + translate.tx, + top: bbox.y * scale.sy + translate.ty, + bottom: (bbox.y + bbox.height) * scale.sy + translate.ty, + }; + const midX = (op.left + op.right) / 2; + const midY = (op.top + op.bottom) / 2; + + const corner = this.pinnedResultPosition(pinned); + const size = this.pinnedWindowSize(pinned.operatorId); + const win = { left: corner.x, right: corner.x + size.width, top: corner.y, bottom: corner.y + size.height }; + const headerY = win.top + PINNED_HEADER_HEIGHT / 2; + + const curve = (x1: number, y1: number, x2: number, y2: number, horizontal: boolean) => { + const bend = Math.max(30, (horizontal ? Math.abs(x2 - x1) : Math.abs(y2 - y1)) / 2); + const [bx, by] = horizontal ? [Math.sign(x2 - x1) * bend, 0] : [0, Math.sign(y2 - y1) * bend]; + return `M ${x1} ${y1} C ${x1 + bx} ${y1 + by}, ${x2 - bx} ${y2 - by}, ${x2} ${y2}`; + }; + if (win.left >= op.right) return curve(op.right, midY, win.left, headerY, true); + if (win.right <= op.left) return curve(op.left, midY, win.right, headerY, true); + // the window overlaps the operator's column: join the facing edges, at the point under the operator + const x = Math.min(Math.max(midX, win.left + 12), win.right - 12); + return win.top >= op.bottom ? curve(midX, op.bottom, x, win.top, false) : curve(midX, op.top, x, win.bottom, false); + } + + /** A pinned window's size as drawn: the user can resize it, so it is read from the page. */ + private pinnedWindowSize(operatorId: string): { width: number; height: number } { + const host = this.elementRef.nativeElement as HTMLElement; + const box = host.querySelector<HTMLElement>(`[data-operator-id="${operatorId}"] .pinned-result`); + return { width: box?.offsetWidth ?? 0, height: box?.offsetHeight ?? 0 }; + } + /** Just right of the operator's box, level with its top, in the editor's coordinates. */ private operatorAnchor(operatorId: string): { x: number; y: number } { const cell = this.paper.getModelById(operatorId); diff --git a/frontend/src/jsdom-svg-polyfill.ts b/frontend/src/jsdom-svg-polyfill.ts index 51e8908964..2a21e16408 100644 --- a/frontend/src/jsdom-svg-polyfill.ts +++ b/frontend/src/jsdom-svg-polyfill.ts @@ -220,6 +220,13 @@ G.ResizeObserver ??= class { disconnect(): void {} }; +// `ClipboardItem` — jsdom doesn't implement it; once a spec has loaded monaco, +// its WebKit clipboard workaround builds one on every click on the page, and +// specs share the page within a worker. +G.ClipboardItem ??= class { + constructor(public items: unknown) {} +}; + // `window.getComputedStyle(elt, pseudoElt)` and `window.scrollTo` — jsdom // implements neither. Both route through its `notImplemented` helper, which // emits a `jsdomError` on the virtual console; vitest's jsdom environment
