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-8846-1d7c00616a5494792e26bb3e9b353dac6b85d62c in repository https://gitbox.apache.org/repos/asf/texera.git
commit 4ab9bab2154c1bc445a6a02a5507657b5726039f Author: yangzhang75 <[email protected]> AuthorDate: Thu Nov 19 01:29:21 2026 +0000 fix(workflow-form): let ui-udf-parameters show the form's renames and hides in its columns, and add a parameter to the card's operator (#8846) ### What changes were proposed in this PR? Closes #8763. Part of the Form View feature (#8011); from the #8439 refinements (item 6). `ui-udf-parameters` (the Python UDF parameter table) is exposable, but its renderer hides formly's labels and draws fixed column headers (Value / Name / Type), so the author's per-sub-field overrides from the form (#8438) changed nothing a reader saw: formly expresses a rename as the sub-field's label and a hide as `hide`, and renders both through the field's wrapper, which this widget's cells never go through -- a renamed column kept its old heading, a hidden one kept its heading over an empty cell. Reviewing it turned up more the widget got wrong on a Form View card. The operator property panel is untouched throughout. - **The form publishes what the author decided; the widget asks.** New `common/formly/sub-field-view.ts`: a host that holds per-sub-field decisions publishes them once on the field it hands a widget (`props.subFieldView`, keyed by sub-field path: `{ label, shown }` -- the author's name, or `""` where they kept the one it came with, and whether a reader sees the part at all), and a widget that draws its own chrome asks `subFieldsInView` / `subFieldLabel`. Reading the state back out of the rendered rows was not the answer: it is only there once formly has built a row, so a table whose UDF declares nothing yet had nothing to read, and a group's hide is marked on the group while its children are merely not rendered. The Form View fills the map during its override walk (the first node met for a path answers for it, as it does for the controls: the rows of a repeated section share one override), `shown` for an author always (who keeps a hidden sub-field on screen, faded, to bring it back) and for a reader unless the override hides it; a hide of the `attribute` group takes both its columns out. A name being typed is written into the very object the field carries, so a header follows the typing without a rebuild; an emptied box deletes the override and the header falls back to the widget's own name. Nothing published -- the panel, where there is no author -- means every part in view under the widget's own name, which is what its fixed headers already say. - **The widget's columns and headers follow it on a card.** `columns` is read live (the form hands the widget its field after the widget's first check) through `subFieldsInView`, which hands back the same array instance while the answer has not changed so the header's `ngFor` does not redraw; a header reads `subFieldLabel` with the fixed label as fallback -- the author's name, else "Type", never the schema's "Attribute Type", which the panel does not show either. All three columns come back while the draft row is open: that row names and types the parameter being added, so it needs them whatever the author hid (Copilot on this PR: a filtered header over its three cells put the name box under the wrong heading). - **A column's label controls live in the header, once** (second commit; found on the running instance while authoring). The form's label wrapper decorates every row's sub-fields -- the first row with the name box and the eye, every later row with a static name -- and this widget drew them in its cells under the header that now reads the author's name, so a column's name was drawn three times over (header, first-row box, each later row's static label; and the static one said "Attribute Type" where the header said "Type"). The wrapper gains one prop, `labelHosted`: a host that draws the label itself sets it, and the wrapper then renders no box, eye or static label, only the control's accessible name (sr-only, tied to the control by `for`, or the group twin for a repeated field) and the dimmed state. The widget hosts the one name box and eye per column in its header, bound to the first row's props and callbacks (`authorName` / `authorHidden` / `renameField` / `setFieldHidden` -- the row the form gave the controls to), and for each column it hosts marks every cell of that column, named as the heading reads. The write-through those controls make (the props first, then the form) and the box's and eye's styles have one definition each, on the wrapper (`EditableLabelWrapperComponent.rename` / `setHidden`; `_editable-label.scss`), which the header uses rather than copies. How a later row's own name keeps up with a rename is the form's `followersByPath`, as before. A renderer with no header of its own (the generic array widget) sets nothing and is untouched; the panel carries no operator mark, so nothing is hosted or marked there. - **The form names the operator on every field it renders** (`props.operatorID`: `FIELD_OPERATOR_ID_PROP` / `fieldOperatorID` / `renderedInFormView` in `custom-formly-type.ts`), since nothing is highlighted on the form; the same mark tells a shared widget which host it is on, where the two must differ. - **"Add parameter" works on a card as on the panel.** It inserts a declaration into an operator's code, and it took that operator from the canvas highlight -- on the form nothing is highlighted, or another step is, so it edited the wrong operator or failed with "code is not available". It now adds to the field's operator on a card and to the highlighted one on the panel. Whether a card offers it (`editable`) asks the two halves of the canvas's rule separately, because the canvas's flag answers neither one on that page. Write access: the card is not a reader's, which the form marks on the field itself (`props.disabled`; `renderedReadOnly`). So a writer's card offers it in and out of edit mode, as every value on the card can be edited, and adding a parameter is adding a row; it followed the canvas's modification flag, which the Form View holds off outside edit mode against structural edits through its page, so a writer could edit every value on the page but not add a parameter to this table without entering edit mode. No run in flight: asked of the execute service, which owns that rule (`isExecutionInFlight()`, lifted out of the switch that already locks the graph, so the states are listed once). Adding a parameter writes into the UDF's code, and code is what a run must not have rewritten under it. The mark decides rather than the table's own control, which does not answer the question: formly disables the leaf controls under a disabled field, not the array itself, so a reader's table with no parameters yet reads as enabled and would have offered the button. The check also sits in the method, not only on the button. The panel keeps the canvas's rule, the flag, unchanged. - **The declared parameters then reach the operator.** The parser announces the UI parameters a UDF's code declares, and the operator property panel's frame writes them onto the operator for the operator it shows, only while it acts as the editor. With the panel closed or on another step nobody wrote them, so a parameter added from a card changed the code but no row appeared. The form writes them when the frame does not: a writer only, not while the step panel shows that very step live, and only for an operator still on the graph; the same value the frame writes. The card showing them is then rebuilt right after the current tick (once every writer has written; held while the reader is typing, and flushing a card's pending write first, as every rebuild is since #8845): it would otherwise have kept its old rows until the compilation result rebuilt it, half a second and a round trip later, and a value typed into it in that window would have gone back with the old rows, dropping the one just declared. - **A read-only reader's value cells are locked**: the Form View marks a reader's field `props.disabled`, and the widget's own "the value is editable" used to re-enable the control after formly had disabled it. ### Any related issues, documentation, discussions? Closes #8763. Raised by Copilot on #8438; filed from #8439. Rebased on main, which now has #8848 (the widget's lock on the Name and Type cells holding under the panel's wholesale `enable()`, split out of an earlier revision of this PR) and #8845 (a card's pending write is flushed before every rebuild, which the catch-up rebuild here inherits; an earlier revision listed that as #8844, open then). #8760 (the form's own code editor host) needs the same operator mark and the same write of the declared parameters; whichever lands second drops its copy. Checked under real formly while reviewing: hiding the `attribute` group itself keeps the rows' names and types in the model (formly resets a hidden field's children only on a hide that happens after the build; the form sets `hide` at build only, and a reader's card is rebuilt rather than toggled). Table semantics for assistive tech (the header and cells are plain `div`s, as on the canvas) stay a follow-up. The remaining stale-row window is a collaborator declaring a parameter while this user types in that same card, where the rebuild is held and the card's write-back puts the old list back; closing it means a card writing only its own key into the operator's current value instead of replacing the whole property, which is a change to every property's write-back and belongs in its own PR. Seen in review, the Form View's own and not changed here: the form's array widget (`ArrayTypeComponent`) shows its add and remove buttons to a reader too, without a write-back behind them; that goes to a follow-up issue. And on main, renaming or hiding a repeated section's sub-field reaches only its first row at once: `followersByPath` registers the configs the section's builder returns, which formly clones before rendering, so the rows on screen never hear of the edit until a rebuild shows the saved override on every row. Pre-existing, found while checking the second commit, which hosts the first row's controls and leaves that mechanism as it is; it goes to its own issue. An earlier revision of this PR let a run through. It described a writer's cards as editable mid-run and read the button as following from that, which holds for the values -- they were always editable here -- but not for this button: the canvas's flag had been hiding it during a run, and dropping the flag dropped that with it. A declaration goes into the UDF's own code, straight into the shared document and not through the graph's lock, and the property panel and the canvas code editor both refuse a code edit while a run is in flight (mengw15). The card now asks for that half on its own; see the rule above. ### How was this PR tested? Unit tests (vitest), added or extended in this PR; every statement, function and branch the PR adds is covered, with the rule for Add parameter pinned once, under real formly, rather than again by hand. - `sub-field-view.spec.ts`: a host that publishes nothing leaves every part in view under the widget's own name; a publishing host drops what the author hid and keeps the rest in the widget's order, gives the author's name and the widget's own where the author kept it, and keeps, and names, a part it did not mention; the same array comes back while the answer has not changed and a new one once it has, each host's answer kept apart; a published value that is not a map is ignored. - The widget's spec: it is on the panel until formly hands it a field and on the form once the field names its operator (and hosts no controls before then); a renamed column shows under its new name and a hidden one is left out, in the header and the cells; the three fixed columns come back while the draft row is open; rows formly builds on demand; a hidden group takes its columns out; the author's name shows while renaming and follows the typing; a table whose UDF declares nothing yet; the panel keeps its fixed headers whatever the sub-fields carry, and the fixed name for a column the author did not rename whatever the schema calls it; the columns are read live, and the same list comes back while nothing changed; a reader's value cells are locked; Add parameter adds to the card's operator on a writer's card, the canvas's flag off, and on the panel to the highlighted one; on a card that is not editable (a reader's, or a writer's while a run is in flight) the method adds nothing, whoever calls, and the draft stays open; on the panel nothing is added while modification is off. Second commit: the header hosts one name box and one eye per column, seeded from the first row, and every cell of every row is marked and named as the heading reads; typing in the header renames through that column's first-row callback and the box follows, the other columns' callbacks untouched; the eye hides through that column's callback, the column fades and stays in view and the eye says so, a second click un-hides; no eye for a column the form marked not hideable, and the mark survives a re-populate; a reader's card and the panel keep a plain text header with no cell marked. - The widget's formly spec (the table stood up under `FormlyModule.forRoot`, a builder row template as formly-jsonschema produces, `nz-input` cells as in the app, so the rows are formly's own and a reader's lock is the one formly applied): a writer's Form View card offers Add parameter without the canvas's flag and a reader's card, its field disabled, does not; the same with no parameters yet, where formly leaves the empty array control enabled; a run in flight takes the button off a writer's card and leaves the values editable. - The wrapper's spec: with `labelHosted`, the row that carries the controls draws no box or eye but is still named and still fades when hidden; a later row draws no static name, only the sr-only one tied to the control by `for`, or the group twin with its `-label` id for a repeated field; `rename` / `setHidden` write the props and then call the form, and tolerate a reader mount that has neither callback. - The form's spec: every field carries its operator; the declared UI parameters are written for a writer when the step panel is not editing that step, left to the frame while it shows the step live (the card still rebuilt), written when it shows the step read-only, and not written for a reader or a vanished operator; the cards are rebuilt after the current tick when one shows that step's parameters, through buildForm (the old cards cut off, the card holding the declared rows), held while the reader is typing and run once the focus leaves, and left alone when none shows that step's parameters or the one that does is another step's; a sub-field formly built without props is renamed; a name being typed lands in the published view on the field itself, a rename for a path the view does not carry is ignored, an author is told a hidden sub-field is still in view and a reader that it is not, and no name is published for a sub-field the author did not rename. - The execute service's spec pins `isExecutionInFlight` against the graph lock, state by state; `custom-formly-type`'s spec pins `fieldOperatorID`, `renderedInFormView` and `renderedReadOnly`. eslint, prettier and the production (AOT) build pass; the full frontend suite passes. Checked on a flag-on instance (main-demo; a Python source feeding a Python UDF whose code declares two UI parameters, `uiParameters` exposed with the Name column renamed "Parameter" and the Type column hidden), the canvas and the form open side by side, main against this branch. On main the card shows Value / Name / Type, the overrides ignored. With this PR the card shows Value / Parameter, the Type column gone, while the canvas panel still shows Value / Name / Type. A writer's card offers Add parameter in and out of edit mode (on main it appeared only in edit mode, while any list's rows could be added either way); adding `cutoff` (double) inserts `self.UiParameter(name="cutoff", type=AttributeType.DOUBLE)` into that UDF's code, and the new row appears on the card and in the canvas tab's panel within a few seconds, and is there after a reload. In edit mode, the first commit alone drew 3 header titles, 3 name boxes and 3 eyes in the first row and 3 static labels in the second; with the second, the header holds the 3 name boxes and 3 eyes and the cells hold none, and a hidden column's header fades with its cells. The canvas panel shows the same three columns, the same values and the same behaviour as on main, side by side on both instances. #### Video **Before** https://github.com/user-attachments/assets/717f73d3-4923-474d-a337-1ae5e8944649 **After** https://github.com/user-attachments/assets/69b5330b-e212-4216-a1d8-63753c38f32d ### Was this PR authored or co-authored using generative AI tooling? Yes. Generated-by: Claude Code (Claude Fable 5.1, Anthropic). Co-authored with Claude, reviewed line by line by the author before submission. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.1 <[email protected]> --- ...wrapper.component.scss => _editable-label.scss} | 44 +- .../editable-label-wrapper.component.html | 23 +- .../editable-label-wrapper.component.scss | 56 +-- .../editable-label-wrapper.component.spec.ts | 60 +++ .../editable-label-wrapper.component.ts | 38 +- .../src/app/common/formly/sub-field-view.spec.ts | 117 +++++ frontend/src/app/common/formly/sub-field-view.ts | 99 +++++ .../ui-udf-parameters.component.formly.spec.ts | 72 +++- .../ui-udf-parameters.component.html | 39 +- .../ui-udf-parameters.component.scss | 24 ++ .../ui-udf-parameters.component.spec.ts | 469 ++++++++++++++++++++- .../ui-udf-parameters.component.ts | 165 +++++++- .../workflow-form/workflow-form.component.spec.ts | 295 ++++++++++++- .../workflow-form/workflow-form.component.ts | 100 ++++- .../workflow-form/workflow-form.rendered.spec.ts | 2 + .../workflow-form/workflow-form.spec-harness.ts | 6 + .../execute-workflow.service.spec.ts | 31 ++ .../execute-workflow/execute-workflow.service.ts | 8 +- .../app/workspace/util/custom-formly-type.spec.ts | 37 +- .../src/app/workspace/util/custom-formly-type.ts | 33 ++ 20 files changed, 1585 insertions(+), 133 deletions(-) diff --git a/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.scss b/frontend/src/app/common/formly/editable-label-wrapper/_editable-label.scss similarity index 61% copy from frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.scss copy to frontend/src/app/common/formly/editable-label-wrapper/_editable-label.scss index b0a1201283..16c3b91e34 100644 --- a/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.scss +++ b/frontend/src/app/common/formly/editable-label-wrapper/_editable-label.scss @@ -17,16 +17,11 @@ * under the License. */ -.lbl-row { - display: flex; - align-items: center; - gap: 6px; - margin-bottom: 2px; -} +/* The author's two label controls -- the dashed name box and the quiet eye -- as one definition, + so a host that draws them itself (a table's column header, see props.labelHosted) shows the same + control the wrapper draws everywhere else, and a change to either lands in both. */ -/* A faint dashed box at rest signals the title is editable (authors could not tell it was - a field before); it firms up on hover and turns into a real input on focus. */ -.lbl-input { +@mixin editable-label-input { flex: 1; min-width: 0; border: 1px dashed #dcdcdc; @@ -56,7 +51,7 @@ } } -.lbl-eye { +@mixin editable-label-eye { flex: none; border: 0; background: none; @@ -83,32 +78,3 @@ color: #1890ff; } } - -/* Present for assistive technology only: the visible name box is the label's editor, not the - control's label. Standard visually-hidden recipe: off-layout, clipped, never display:none (which - would remove it from the accessibility tree too). */ -.lbl-sr-only { - position: absolute; - width: 1px; - height: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip: rect(0, 0, 0, 0); - white-space: nowrap; - border: 0; -} - -.lbl-static { - display: block; - font-size: 13px; - color: rgba(0, 0, 0, 0.85); - margin-bottom: 2px; -} - -/* A hidden field stays visible to its author, faded, so they can see what they removed - and put it back. The reader never renders it at all. Faded to 0.6, not further: the field is - still operable while hidden, so its text has to stay readable. */ -.dimmed { - opacity: 0.6; -} diff --git a/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.html b/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.html index 3e667f669f..58c4a6fc9a 100644 --- a/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.html +++ b/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.html @@ -20,9 +20,12 @@ <!-- Authoring: the label is the input, so what you type is what the reader reads. Written through on every keystroke (input, not change): the hidden label below and the saved name follow the box as it is typed, so nothing is lost if the page is left while the box still has the focus. --> +<!-- A host that draws this field's label itself (a table's column header) sets labelHosted: the + controls live there, bound to this field's props, so nothing visible is drawn here -- only the + name for assistive technology below, and the dimmed state. --> <div class="lbl-row" - *ngIf="props.authoring"> + *ngIf="props.authoring && !props.labelHosted"> <input class="lbl-input" [value]="props.authorName" @@ -75,13 +78,27 @@ row's name box and eye (and fades with them when hidden), without controls of its own. --> <label class="lbl-static" - *ngIf="!props.authoring && !props.labelsGroup && (props.authorName || props.schemaLabel)" + *ngIf="!props.authoring && !props.labelHosted && !props.labelsGroup && (props.authorName || props.schemaLabel)" [attr.for]="id"> {{ props.authorName || props.schemaLabel }} </label> <span class="lbl-static" - *ngIf="!props.authoring && props.labelsGroup && (props.authorName || props.schemaLabel)" + *ngIf="!props.authoring && !props.labelHosted && props.labelsGroup && (props.authorName || props.schemaLabel)" + [id]="id + '-label'"> + {{ props.authorName || props.schemaLabel }} +</span> +<!-- Hosted elsewhere, without the controls: a later row of a repeated section while authoring. The + first row's controls, hosted by the table, carry the name; this row's control still needs one. --> +<label + class="lbl-sr-only" + *ngIf="!props.authoring && props.labelHosted && !props.labelsGroup" + [attr.for]="id"> + {{ props.authorName || props.schemaLabel }} +</label> +<span + class="lbl-sr-only" + *ngIf="!props.authoring && props.labelHosted && props.labelsGroup" [id]="id + '-label'"> {{ props.authorName || props.schemaLabel }} </span> diff --git a/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.scss b/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.scss index b0a1201283..f0c5cee737 100644 --- a/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.scss +++ b/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.scss @@ -17,6 +17,8 @@ * under the License. */ +@use "./editable-label" as *; + .lbl-row { display: flex; align-items: center; @@ -27,61 +29,11 @@ /* A faint dashed box at rest signals the title is editable (authors could not tell it was a field before); it firms up on hover and turns into a real input on focus. */ .lbl-input { - flex: 1; - min-width: 0; - border: 1px dashed #dcdcdc; - border-radius: 4px; - background: none; - padding: 1px 5px; - font-size: 13px; - font-weight: 500; - color: rgba(0, 0, 0, 0.85); - outline: none; - cursor: text; - - &::placeholder { - color: rgba(0, 0, 0, 0.45); - font-weight: 400; - } - - &:hover { - border-style: solid; - border-color: #b0b0b0; - } - - &:focus { - border-style: solid; - border-color: #1890ff; - background: #fff; - } + @include editable-label-input; } .lbl-eye { - flex: none; - border: 0; - background: none; - cursor: pointer; - line-height: 0; - padding: 3px; - border-radius: 4px; - color: rgba(0, 0, 0, 0.45); - font-size: 14px; - - &:hover { - color: rgba(0, 0, 0, 0.85); - background: #f5f5f5; - } - - &:focus-visible { - outline: 2px solid #1890ff; - outline-offset: 1px; - } - - /* Hidden is a state worth seeing at a glance, so it keeps the accent rather than - fading like the rest of the row. */ - &.off { - color: #1890ff; - } + @include editable-label-eye; } /* Present for assistive technology only: the visible name box is the label's editor, not the diff --git a/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.spec.ts b/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.spec.ts index 4801dcbd8d..9be81a93a8 100644 --- a/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.spec.ts +++ b/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.spec.ts @@ -228,6 +228,66 @@ describe("EditableLabelWrapperComponent", () => { expect(fixture.nativeElement.querySelector("button.lbl-eye")).toBeNull(); }); + // A host that draws the label itself (a table's column header) marks the field labelHosted: the + // controls live in the host, bound to these same props, so drawing them here too put the one + // name three times over -- the header, the first row's box, every later row's static label. + it("draws nothing visible when the host draws the label: the first row's controls, and a later row's static name", () => { + // The row that carries the controls: no box, no eye; still named, still fades when hidden. + component.field = { + props: { authoring: true, labelHosted: true, authorName: "Genes", schemaLabel: "File Key", authorHidden: true }, + } as unknown as FormlyFieldConfig; + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector(".lbl-row")).toBeNull(); + expect(fixture.nativeElement.querySelector(".lbl-sr-only")?.textContent?.trim()).toBe("Genes"); + expect(fixture.nativeElement.querySelector(".dimmed")).not.toBeNull(); + + // A later row (decorated without the controls): no static name either, only the accessible one. + component.field = { + id: "genes-1", + props: { authoring: false, labelHosted: true, authorName: "Genes", schemaLabel: "File Key" }, + } as unknown as FormlyFieldConfig; + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector(".lbl-static")).toBeNull(); + const label = fixture.nativeElement.querySelector("label.lbl-sr-only") as HTMLLabelElement; + expect(label.textContent?.trim()).toBe("Genes"); + expect(label.getAttribute("for")).toBe("genes-1"); + + // A hosted repeated field is named as a group, like an unhosted one. + component.field = { + id: "genes-1", + props: { authoring: false, labelHosted: true, labelsGroup: true, authorName: "Genes", schemaLabel: "File Key" }, + } as unknown as FormlyFieldConfig; + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector("label.lbl-sr-only")).toBeNull(); + const group = fixture.nativeElement.querySelector("span.lbl-sr-only") as HTMLSpanElement; + expect(group.textContent?.trim()).toBe("Genes"); + expect(group.id).toBe("genes-1-label"); + }); + + // The write-through a host's own box and eye go through, so a rename or a hide lands the same + // way wherever the control is drawn: on the props first, then to the form. + it("rename and setHidden write the props and then call the form, and tolerate a reader mount", () => { + const rename = vi.fn(); + const setHidden = vi.fn(); + const props: Record<string, unknown> = { + authorName: "a", + authorHidden: false, + renameField: rename, + setFieldHidden: setHidden, + }; + EditableLabelWrapperComponent.rename(props, "b"); + expect(props["authorName"]).toBe("b"); + expect(rename).toHaveBeenCalledWith("b"); + EditableLabelWrapperComponent.setHidden(props, true); + expect(props["authorHidden"]).toBe(true); + expect(setHidden).toHaveBeenCalledWith(true); + + const reader: Record<string, unknown> = { authorName: "a", authorHidden: false }; + expect(() => EditableLabelWrapperComponent.rename(reader, "c")).not.toThrow(); + expect(() => EditableLabelWrapperComponent.setHidden(reader, true)).not.toThrow(); + expect(reader["authorName"]).toBe("c"); + }); + it("for a reader, renders a plain static label from authorName, tied to the control by id", () => { // decorate blanks formly's own label, so this one is the control's only label: without `for` // the reader's input would show a name but have no accessible name at all. diff --git a/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.ts b/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.ts index feebd82aa7..6d7444efb8 100644 --- a/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.ts +++ b/frontend/src/app/common/formly/editable-label-wrapper/editable-label-wrapper.component.ts @@ -36,6 +36,11 @@ import { merge } from "lodash-es"; imports: [NgIf, NzIconDirective], }) export class EditableLabelWrapperComponent extends FieldWrapper { + /** A host that draws the label itself sets `props.labelHosted` on the field after decorate(): the + * wrapper then renders no name box, eye or static label, only the control's accessible name and + * the dimmed state, and the host binds its own controls to the same props and callbacks. */ + public static readonly LABEL_HOSTED_PROP = "labelHosted"; + /** Add this wrapper to a field with its naming + callbacks; `fallback` (the schema label) * is the placeholder, so the author sees what leaving it blank yields. `rename` may be omitted * for a reader mount (`authoring: false`), which renders a static label and no name input; @@ -68,23 +73,36 @@ export class EditableLabelWrapperComponent extends FieldWrapper { }); } + /** + * The write-through a rename follows, wherever the box is drawn: the name lands on the props + * first, so everything bound to them (this wrapper's hidden label, a host's header, the later + * rows the form keeps in step) shows it without a rebuild, and only then does the form hear of + * it. A host that draws the box itself (props.labelHosted) calls this rather than copying it. + */ + public static rename(props: Record<string, unknown>, value: string): void { + props["authorName"] = value; + // Optional-chained: a reader mount omits rename and never renders the box this serves, but the + // write-through should not depend on that. + (props["renameField"] as ((name: string) => void) | undefined)?.(value); + } + + /** The hide toggle's write-through; see rename. */ + public static setHidden(props: Record<string, unknown>, hidden: boolean): void { + props["authorHidden"] = hidden; + // Optional-chained: decorate may omit setHidden when canHide is false, and although the control + // is not rendered then, a plain call would couple that to luck. + (props["setFieldHidden"] as ((hidden: boolean) => void) | undefined)?.(hidden); + } + public onRename(event: Event): void { // The wrapper reflects the edit itself (the hidden label follows authorName), so the page does // not rebuild the form for a rename and the author keeps the focus where it is. - const value = (event.target as HTMLInputElement).value; - this.props["authorName"] = value; - // Optional-chained for the same reason as setFieldHidden below: a reader mount omits rename and - // never renders the input this handles, but the handler should not depend on that. - this.props["renameField"]?.(value); + EditableLabelWrapperComponent.rename(this.props, (event.target as HTMLInputElement).value); } public onToggleHidden(): void { // Same as onRename: the eye, the pressed state and the faded field follow authorHidden here, so // no rebuild is needed and the focus stays on the eye. - const hidden = !this.props["authorHidden"]; - this.props["authorHidden"] = hidden; - // Optional-chained: decorate may omit setHidden when canHide is false, and although this handler - // is unreachable then (the hide control is not rendered), a plain call would couple that to luck. - this.props["setFieldHidden"]?.(hidden); + EditableLabelWrapperComponent.setHidden(this.props, !this.props["authorHidden"]); } } diff --git a/frontend/src/app/common/formly/sub-field-view.spec.ts b/frontend/src/app/common/formly/sub-field-view.spec.ts new file mode 100644 index 0000000000..8f3c9d5482 --- /dev/null +++ b/frontend/src/app/common/formly/sub-field-view.spec.ts @@ -0,0 +1,117 @@ +/** + * 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 { describe, expect, it } from "vitest"; +import { SUB_FIELD_VIEW_PROP, subFieldLabel, subFieldsInView, subFieldViews } from "./sub-field-view"; + +describe("sub-field view", () => { + const parts = [ + { path: "value", label: "Value" }, + { path: "attribute.attributeName", label: "Name" }, + { path: "attribute.attributeType", label: "Type" }, + ] as const; + + const host = (view?: Record<string, { label: string; shown: boolean }>) => ({ + props: view === undefined ? {} : { [SUB_FIELD_VIEW_PROP]: view }, + }); + + describe("a host that publishes nothing", () => { + // The operator property panel: no author, no overrides, so a widget's own headers are the answer. + it("leaves every part in view, under the widget's own name", () => { + const field = host(); + expect(subFieldViews(field)).toBeUndefined(); + expect(subFieldsInView(field, parts)).toBe(parts); + expect(subFieldLabel(field, "attribute.attributeName", "Name")).toBe("Name"); + }); + }); + + describe("a host that publishes", () => { + it("drops what the author hid and keeps the rest in the widget's order", () => { + const field = host({ + value: { label: "Value", shown: true }, + "attribute.attributeName": { label: "Parameter", shown: true }, + "attribute.attributeType": { label: "Type", shown: false }, + }); + + expect(subFieldsInView(field, parts).map(p => p.path)).toEqual(["value", "attribute.attributeName"]); + }); + + it("gives the author's name, and the widget's own where the author kept it", () => { + const field = host({ + "attribute.attributeName": { label: "Parameter", shown: true }, + "attribute.attributeType": { label: "Type", shown: true }, + }); + + expect(subFieldLabel(field, "attribute.attributeName", "Name")).toBe("Parameter"); + expect(subFieldLabel(field, "attribute.attributeType", "Type")).toBe("Type"); + }); + + // A part the host said nothing about is one the author was never offered, not one they hid. + it("keeps a part the host did not mention", () => { + const field = host({ "attribute.attributeType": { label: "Type", shown: false } }); + + expect(subFieldsInView(field, parts).map(p => p.path)).toEqual(["value", "attribute.attributeName"]); + }); + + it("falls back to the widget's name for a part the host did not mention", () => { + expect(subFieldLabel(host({}), "value", "Value")).toBe("Value"); + }); + }); + + // A widget reads this from its template, so it runs on every check; a new array each time would + // have an ngFor tear its header down and rebuild it, losing the focus in a cell being used. + describe("identity", () => { + it("returns the same array while the answer has not changed", () => { + const field = host({ "attribute.attributeType": { label: "Type", shown: false } }); + + const first = subFieldsInView(field, parts); + expect(subFieldsInView(field, parts)).toBe(first); + }); + + it("returns a new array once the answer changes", () => { + const field = host({ "attribute.attributeType": { label: "Type", shown: false } }); + const first = subFieldsInView(field, parts); + + field.props = { + [SUB_FIELD_VIEW_PROP]: { + "attribute.attributeType": { label: "Type", shown: true }, + }, + }; + + const second = subFieldsInView(field, parts); + expect(second).not.toBe(first); + expect(second.map(p => p.path)).toEqual(parts.map(p => p.path)); + }); + + it("keeps each host's answer apart", () => { + const hidden = host({ "attribute.attributeType": { label: "Type", shown: false } }); + const whole = host({}); + + expect(subFieldsInView(hidden, parts)).toHaveLength(2); + expect(subFieldsInView(whole, parts)).toHaveLength(3); + expect(subFieldsInView(hidden, parts)).toHaveLength(2); + }); + }); + + it("ignores a published value that is not a map", () => { + expect(subFieldViews({ props: { [SUB_FIELD_VIEW_PROP]: "nonsense" } })).toBeUndefined(); + expect(subFieldViews({ props: { [SUB_FIELD_VIEW_PROP]: [] } })).toBeUndefined(); + expect(subFieldViews({ props: {} })).toBeUndefined(); + expect(subFieldViews({})).toBeUndefined(); + }); +}); diff --git a/frontend/src/app/common/formly/sub-field-view.ts b/frontend/src/app/common/formly/sub-field-view.ts new file mode 100644 index 0000000000..5780928681 --- /dev/null +++ b/frontend/src/app/common/formly/sub-field-view.ts @@ -0,0 +1,99 @@ +/** + * 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. + */ + +/** + * What the Form View's author decided about each sub-field of an exposed input, resolved for the + * reader in front of it, for a widget that draws its own chrome. + * + * Formly expresses a rename as the field's label and a hide as `hide`, and renders both through the + * field's wrapper. A widget that renders its sub-fields itself -- a table with its own column + * headers, a legend, a summary line -- never goes through that wrapper, so it shows neither: a + * renamed column keeps its old heading, and a hidden one keeps its heading over an empty cell + * (#8763). Reading the state back out of the rendered fields is not the answer either: it is only + * there once formly has built a row, so a table whose operator declares nothing yet has nothing to + * read, and a group's hide is marked on the group while its children are merely not rendered. + * + * So the page that holds the author's decisions publishes them, once, on the field it hands the + * widget ({@link SUB_FIELD_VIEW_PROP}), and the widget asks here. Nothing published -- the operator + * property panel, where there is no author and no overrides -- means every sub-field is in view + * under its own name, which is what a widget's fixed headers already say. + */ +export interface SubFieldView { + /** + * The name the author gave this sub-field, or "" where they kept the one it came with: a widget + * has a name of its own for the part it draws (a table's column heading) and keeps it then. + */ + readonly label: string; + /** Whether this sub-field is in view at all. False only for a reader looking at a hidden one. */ + readonly shown: boolean; +} + +/** Where a host publishes {@link SubFieldView}s, keyed by sub-field path, in the field's `props`. */ +export const SUB_FIELD_VIEW_PROP = "subFieldView"; + +/** What the host published for this field, if it is a host that publishes. */ +export function subFieldViews(field: { + props?: Record<string, unknown>; +}): Readonly<Record<string, SubFieldView>> | undefined { + const published = field.props?.[SUB_FIELD_VIEW_PROP]; + return typeof published === "object" && published !== null && !Array.isArray(published) + ? (published as Readonly<Record<string, SubFieldView>>) + : undefined; +} + +/** A sub-field's name: the author's where they gave one, else the one the widget draws itself. */ +export function subFieldLabel(field: { props?: Record<string, unknown> }, path: string, fallback: string): string { + const label = subFieldViews(field)?.[path]?.label; + return label ? label : fallback; +} + +/** + * The parts of a widget's own layout the reader should see, in the widget's order: everything, bar + * what the author hid. A part the host said nothing about stays -- it is one the author was never + * offered, not one they hid. + * + * The same array instance comes back while the answer has not changed, so a widget may call this + * from its template (the state arrives after the first check, so it has to be read live) without + * an `ngFor` tearing its rows down on every pass. + */ +export function subFieldsInView<T extends { readonly path: string }>( + field: { props?: Record<string, unknown> }, + parts: readonly T[] +): readonly T[] { + const views = subFieldViews(field); + const next = views === undefined ? parts : parts.filter(part => shown(views, part.path)); + const previous = lastInView.get(field) as readonly T[] | undefined; + if (previous !== undefined && previous.length === next.length && previous.every((p, i) => p === next[i])) { + return previous; + } + lastInView.set(field, next); + return next; +} + +/** + * Whether a path is in view: its own entry, and every group it sits in. Hiding a group hides what + * is inside it, and the author hid the group, so that is the entry the host published. + */ +function shown(views: Readonly<Record<string, SubFieldView>>, path: string): boolean { + const segments = path.split("."); + return segments.every((_, i) => views[segments.slice(0, i + 1).join(".")]?.shown !== false); +} + +/** Per field, the array {@link subFieldsInView} last returned, so an unchanged answer keeps its identity. */ +const lastInView = new WeakMap<object, readonly unknown[]>(); diff --git a/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.formly.spec.ts b/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.formly.spec.ts index a3d7c75314..106f31bce5 100644 --- a/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.formly.spec.ts +++ b/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.formly.spec.ts @@ -24,6 +24,7 @@ import { FieldType, FieldTypeConfig, FormlyFieldConfig, FormlyForm, FormlyModule import { NzInputModule } from "ng-zorro-antd/input"; import { NotificationService } from "../../../common/service/notification/notification.service"; import { UiUdfParametersSyncService } from "../../service/code-editor/ui-udf-parameters-sync.service"; +import { ExecuteWorkflowService } from "../../service/execute-workflow/execute-workflow.service"; import { WorkflowActionService } from "../../service/workflow-graph/model/workflow-action.service"; import { UiUdfParametersComponent } from "./ui-udf-parameters.component"; @@ -73,13 +74,23 @@ class HostComponent { } /** - * Real formly, no mocks of it: the operator property panel enables and disables its whole form - * group (setInteractivity), and formly mirrors a control's state into props.disabled, so the - * widget's lock on the Name and Type columns has to survive a wholesale enable(). The widget's own - * spec drives populate on hand-made rows; this one proves the lock under formly's own build. + * Real formly, no mocks of it. The widget's own spec drives populate on hand-made rows, which says + * nothing about what formly builds from a row template, what it does with a field the Form View + * marked for a reader, or what survives a host that enables the whole group. This one stands the + * table up the way the app does -- a form, the builder row template formly-jsonschema produces, + * nz-input cells -- so the rows are formly's own: the reader's lock is the one formly applied, and + * the widget's lock on the Name and Type columns has to survive the panel's wholesale enable() + * (setInteractivity), which formly mirrors into props.disabled. */ describe("UiUdfParametersComponent under real formly", () => { + /** The canvas's modification flag, which the Form View holds off outside edit mode. */ + let modificationEnabled = true; + /** Whether a run is in flight, the half of the canvas's rule the flag above no longer carries. */ + let executionInFlight = false; + beforeEach(async () => { + modificationEnabled = true; + executionInFlight = false; await TestBed.configureTestingModule({ imports: [ HostComponent, @@ -94,18 +105,29 @@ describe("UiUdfParametersComponent under real formly", () => { { provide: WorkflowActionService, useValue: { - checkWorkflowModificationEnabled: () => true, + checkWorkflowModificationEnabled: () => modificationEnabled, getJointGraphWrapper: () => ({ getCurrentHighlightedOperatorIDs: () => ["op-1"] }), }, }, { provide: UiUdfParametersSyncService, useValue: { addParameter: vi.fn() } }, { provide: NotificationService, useValue: { error: vi.fn() } }, + { provide: ExecuteWorkflowService, useValue: { isExecutionInFlight: () => executionInFlight } }, ], }).compileComponents(); }); - function render() { + /** + * Renders the host; `topProps` go on the table's field (the Form View puts its marks there), `rows` + * replace the two parameters the model declares by default. + */ + function render(topProps?: Record<string, unknown>, rows?: unknown[]) { const fixture = TestBed.createComponent(HostComponent); + if (topProps) { + fixture.componentInstance.fields[0].props = topProps; + } + if (rows) { + fixture.componentInstance.model = { uiParameters: rows as HostComponent["model"]["uiParameters"] }; + } fixture.detectChanges(); const form = fixture.componentInstance.form; const cell = (row: number, path: string) => form.get(`uiParameters.${row}.${path}`)!; @@ -124,6 +146,44 @@ describe("UiUdfParametersComponent under real formly", () => { expect(locks()).toEqual([false, true, true, true]); }); + const addButton = (fixture: { nativeElement: HTMLElement }) => + fixture.nativeElement.querySelector(".add-parameter-button"); + + it("offers Add parameter on a writer's Form View card without the canvas's flag, and not on a reader's, whose field is disabled", () => { + modificationEnabled = false; + + const writer = render({ operatorID: "op-form" }); + expect(addButton(writer.fixture)).not.toBeNull(); + + const reader = render({ operatorID: "op-form", disabled: true }); + expect(reader.locks()).toEqual([true, true, true, true]); + expect(addButton(reader.fixture)).toBeNull(); + }); + + // formly disables the controls it builds under a disabled field, not the array itself, and an + // array with no rows reads as enabled; the form's mark on the field is what says "a reader's". + it("offers Add parameter to a writer whose UDF declares no parameters yet, and not to a reader, though the empty array control is enabled", () => { + modificationEnabled = false; + + const writer = render({ operatorID: "op-form" }, []); + expect(writer.form.get("uiParameters")!.enabled).toBe(true); + expect(addButton(writer.fixture)).not.toBeNull(); + + const reader = render({ operatorID: "op-form", disabled: true }, []); + expect(reader.form.get("uiParameters")!.enabled).toBe(true); + expect(addButton(reader.fixture)).toBeNull(); + }); + + // A declaration goes into the UDF's code, which a run must not have rewritten under it; the + // values on the card stay editable through a run, as they always were. + it("takes Add parameter off a writer's card while a run is in flight, leaving the values editable", () => { + executionInFlight = true; + + const writer = render({ operatorID: "op-form" }); + + expect(addButton(writer.fixture)).toBeNull(); + expect(writer.locks()).toEqual([false, true, true, true]); + }); // The lock goes back on in the microtask after the host's enable() (see keepLocked), so the // assertions wait one; what the reader sees is read from the inputs, not only the controls. const settled = async (fixture: { detectChanges(): void }) => { diff --git a/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.html b/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.html index e8220aa973..0cfcf49ad6 100644 --- a/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.html +++ b/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.html @@ -19,7 +19,7 @@ <div class="ui-udf-parameters-field"> <button class="add-parameter-button" - *ngIf="workflowModificationEnabled && !draftVisible" + *ngIf="editable && !draftVisible" nz-button nzType="dashed" nzBlock @@ -37,8 +37,39 @@ <div class="ui-udf-parameter-row header"> <div class="field-cell" - *ngFor="let column of fieldColumns"> - <span class="col-title">{{ column.label }}</span> + [class.dimmed]="columnHidden(column)" + *ngFor="let column of columns"> + <!-- Authoring on the Form View: the column's name box and eye, the one pair the form's label + wrapper would have drawn in the first row's cell, hosted here instead (see + hostColumnLabels). Otherwise the header is the column's name. --> + <ng-container *ngIf="columnControls(column) as controls; else plainTitle"> + <div class="col-controls"> + <input + class="col-title-input" + [value]="controls['authorName'] || ''" + [placeholder]="column.label" + (input)="renameColumn(column, $event)" + [attr.aria-label]="'Heading of the ' + column.label + ' column'" + [title]="'Shown as this column\'s heading. Empty keeps ' + column.label" /> + <button + *ngIf="controls['canHide'] !== false" + type="button" + class="col-eye" + [class.off]="controls['authorHidden'] === true" + (click)="toggleColumnHidden(column)" + [attr.aria-pressed]="controls['authorHidden'] === true" + [attr.aria-label]="'Hide the ' + column.label + ' column from the form'" + [title]="controls['authorHidden'] ? 'Hidden from the form' : 'Shown on the form'"> + <span + nz-icon + [nzType]="controls['authorHidden'] ? 'eye-invisible' : 'eye'" + nzTheme="outline"></span> + </button> + </div> + </ng-container> + <ng-template #plainTitle> + <span class="col-title">{{ columnLabel(column) }}</span> + </ng-template> </div> </div> @@ -95,7 +126,7 @@ <ng-container *ngIf="field.fieldGroup?.[i] as rowField"> <div class="field-cell" - *ngFor="let column of fieldColumns"> + *ngFor="let column of columns"> <formly-field *ngIf="getColumnField(rowField, column) as columnField" [field]="columnField"></formly-field> diff --git a/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.scss b/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.scss index a4ccd6039f..dd06c69ba1 100644 --- a/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.scss +++ b/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.scss @@ -17,6 +17,8 @@ * under the License. */ +@use "../../../common/formly/editable-label-wrapper/editable-label" as *; + .ui-udf-parameter-row { display: grid; grid-template-columns: 250px 250px 1fr; @@ -36,6 +38,28 @@ display: none; } +/* The header's name box and eye: the form's own label controls (editable-label-wrapper), drawn here + for a column instead of in its first cell, from the wrapper's own definition so they are the one + control an author meets everywhere, not a copy of it. */ +.col-controls { + display: flex; + align-items: center; + gap: 6px; +} + +.col-title-input { + @include editable-label-input; +} + +.col-eye { + @include editable-label-eye; +} + +/* A hidden column stays in view for its author, faded, as every hidden field on the form does. */ +.field-cell.dimmed { + opacity: 0.6; +} + .ui-udf-parameter-row.draft { align-items: center; diff --git a/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.spec.ts b/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.spec.ts index 7f79d14a50..f666f690de 100644 --- a/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.spec.ts +++ b/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.spec.ts @@ -29,6 +29,7 @@ import { UiUdfParametersParseError, } from "../../service/code-editor/ui-udf-parameters-parser.service"; import { UiUdfParametersSyncService } from "../../service/code-editor/ui-udf-parameters-sync.service"; +import { ExecuteWorkflowService } from "../../service/execute-workflow/execute-workflow.service"; import { WorkflowActionService } from "../../service/workflow-graph/model/workflow-action.service"; import { UiUdfParametersComponent } from "./ui-udf-parameters.component"; @@ -43,6 +44,7 @@ describe("UiUdfParametersComponent", () => { }; let syncServiceMock: { addParameter: Mock }; let notificationServiceMock: { error: Mock }; + let executeServiceMock: { isExecutionInFlight: Mock }; beforeEach(async () => { workflowActionServiceMock = { @@ -53,6 +55,7 @@ describe("UiUdfParametersComponent", () => { }; syncServiceMock = { addParameter: vitest.fn() }; notificationServiceMock = { error: vitest.fn() }; + executeServiceMock = { isExecutionInFlight: vitest.fn().mockReturnValue(false) }; await TestBed.configureTestingModule({ imports: [UiUdfParametersComponent], @@ -60,6 +63,7 @@ describe("UiUdfParametersComponent", () => { { provide: WorkflowActionService, useValue: workflowActionServiceMock }, { provide: UiUdfParametersSyncService, useValue: syncServiceMock }, { provide: NotificationService, useValue: notificationServiceMock }, + { provide: ExecuteWorkflowService, useValue: executeServiceMock }, ], }).compileComponents(); @@ -235,6 +239,10 @@ describe("UiUdfParametersComponent", () => { expect(valueOf(unknownRow)?.type).toBeUndefined(); }); + it("configures no value editor for a row formly has not built", () => { + expect(() => (component as any).configureValueEditor(undefined, "model")).not.toThrow(); + }); + it("should find the rows before Formly narrows the field's model to them", () => { const rows = [{ inputType: "dataset", attribute: { attributeName: "DATA" } }]; const operatorProperties = { code: "", uiParameters: rows }; @@ -326,6 +334,456 @@ describe("UiUdfParametersComponent", () => { }); }); + // The Form View's per-sub-field overrides (#8438) land on a row's sub-fields as props.label and + // hide; this widget hides the formly labels and draws fixed headers, which papered over both (#8763). + describe("on the Form View (props.operatorID set by the form)", () => { + const model = [{ value: "42", attribute: { attributeName: "threshold", attributeType: "double" } }]; + + it("is on the panel until formly hands it a field, and on the form once the field names its operator", () => { + (component as any).field = undefined; + expect(component.onFormView).toBe(false); + // The template may read the columns, and their headers, before formly hands it the field. + expect(component.columns).toBe(component.fieldColumns); + expect(component.columnLabel(component.fieldColumns[1])).toBe("Name"); + expect(component.columnControls(component.fieldColumns[1])).toBeUndefined(); + (component as any).field = { props: { operatorID: "op-form" } }; + expect(component.onFormView).toBe(true); + }); + + /** A row as formly builds it: the cells, which the widget reaches by key. */ + function row(): FormlyFieldConfig { + return { + fieldGroup: [ + { key: "value" }, + { key: "attribute", fieldGroup: [{ key: "attributeName" }, { key: "attributeType" }] }, + ], + }; + } + /** What the Form View publishes on the input's field: the name renamed, the type hidden. */ + const renamedAndHidden = { + value: { label: "Value", shown: true }, + "attribute.attributeName": { label: "Parameter", shown: true }, + "attribute.attributeType": { label: "Type", shown: false }, + }; + /** Populates the widget as formly's build does, and reads the headers as the template does. */ + function populate(field: FormlyFieldConfig): string[] { + (component as any).field = field; + component.onPopulate(field); + return component.columns.map(column => component.columnLabel(column)); + } + const headers = () => + Array.from( + fixture.nativeElement.querySelectorAll(".ui-udf-parameter-row.header .col-title") as NodeListOf<HTMLElement> + ).map(cell => cell.textContent?.trim()); + + /** + * A row as the form's walk decorates it for the AUTHOR. `controls` for the row that carries them + * (each cell with callbacks of its own, so a test can tell which column's fired), `follower` + * for a later row, which shows the same state and has no callbacks. + */ + function authoredRow(carriesControls = true, canHide = true): FormlyFieldConfig { + const controls = (name: string, label: string) => ({ + label: "", + authoring: carriesControls, + authorName: name, + authorHidden: false, + canHide, + schemaLabel: label, + renameField: carriesControls ? vitest.fn() : undefined, + setFieldHidden: carriesControls ? vitest.fn() : undefined, + }); + // A rendered cell's props are observed by formly, which runs field.options.detectChanges on a + // write; the harness has no formly build behind these rows, so give each cell that hook. + const options = { detectChanges: () => {} } as FormlyFieldConfig["options"]; + return { + fieldGroup: [ + { key: "value", props: controls("", "Value"), options }, + { + key: "attribute", + fieldGroup: [ + { key: "attributeName", props: controls("Parameter", "Attribute Name"), options }, + { key: "attributeType", props: controls("", "Attribute Type"), options }, + ], + }, + ], + }; + } + const headerBoxes = () => + Array.from( + fixture.nativeElement.querySelectorAll( + ".ui-udf-parameter-row.header .col-title-input" + ) as NodeListOf<HTMLInputElement> + ); + const headerEyes = () => + Array.from( + fixture.nativeElement.querySelectorAll(".ui-udf-parameter-row.header .col-eye") as NodeListOf<HTMLButtonElement> + ); + + // The form's label wrapper decorates every row's sub-fields; drawn in the cells under a header + // that already names the column, the first row's name box and every later row's static label + // put one name three times over. The header hosts the one pair of controls per column instead. + /** What the form publishes while authoring: every column shown, whatever the author hid. */ + const allShownForAuthor = { + value: { label: "", shown: true }, + "attribute.attributeName": { label: "Parameter", shown: true }, + "attribute.attributeType": { label: "", shown: true }, + }; + + it("hosts the author's name box and eye for each column in its header, and tells the cells so", () => { + const row = authoredRow(); + const later = authoredRow(false); + const field = { + model: [...model, { value: "7", attribute: { attributeName: "limit", attributeType: "integer" } }], + props: { operatorID: "op-form", subFieldView: allShownForAuthor }, + fieldArray: () => row, + fieldGroup: [row, later], + } as FormlyFieldConfig; + populate(field); + fixture.detectChanges(); + + // One name box and one eye per column, in the header, seeded from the first row. + expect(headerBoxes().map(box => box.value)).toEqual(["", "Parameter", ""]); + expect(headerBoxes().map(box => box.placeholder)).toEqual(["Value", "Name", "Type"]); + expect(headerEyes()).toHaveLength(3); + expect(fixture.nativeElement.querySelectorAll(".ui-udf-parameter-row.header .col-title")).toHaveLength(0); + // Every cell of every row is told the label lives in the header, and is named as the heading + // reads, not as the schema does ("Type", not "Attribute Type"). + const cells = (r: FormlyFieldConfig) => [ + r.fieldGroup![0], + r.fieldGroup![1].fieldGroup![0], + r.fieldGroup![1].fieldGroup![1], + ]; + for (const cell of [...cells(row), ...cells(later)]) { + expect(cell.props?.["labelHosted"]).toBe(true); + } + expect(cells(later).map(cell => cell.props?.["schemaLabel"])).toEqual(["Value", "Name", "Type"]); + + // Typing in the header renames through the first row's own callback for THAT column, and the + // box follows; the other columns' callbacks are left alone. + const [value, name, type] = cells(row); + const box = headerBoxes()[1]; + box.value = "Threshold"; + box.dispatchEvent(new Event("input")); + expect(name.props?.["renameField"]).toHaveBeenCalledWith("Threshold"); + expect(name.props?.["authorName"]).toBe("Threshold"); + expect(value.props?.["renameField"]).not.toHaveBeenCalled(); + expect(type.props?.["renameField"]).not.toHaveBeenCalled(); + + // The eye hides through that column's own callback; the column fades and stays in view (the + // form publishes every column shown for an author); the eye says so; a second click un-hides. + headerEyes()[2].click(); + fixture.detectChanges(); + expect(type.props?.["setFieldHidden"]).toHaveBeenCalledWith(true); + expect(type.props?.["authorHidden"]).toBe(true); + expect(name.props?.["setFieldHidden"]).not.toHaveBeenCalled(); + expect(component.columns).toHaveLength(3); + expect(fixture.nativeElement.querySelectorAll(".ui-udf-parameter-row.header .field-cell.dimmed")).toHaveLength(1); + const eye = headerEyes()[2]; + expect(eye.getAttribute("aria-pressed")).toBe("true"); + expect(eye.classList.contains("off")).toBe(true); + expect(eye.getAttribute("title")).toBe("Hidden from the form"); + eye.click(); + fixture.detectChanges(); + expect(type.props?.["setFieldHidden"]).toHaveBeenLastCalledWith(false); + expect(type.props?.["authorHidden"]).toBe(false); + expect(headerEyes()[2].getAttribute("aria-pressed")).toBe("false"); + expect(headerEyes()[2].getAttribute("title")).toBe("Shown on the form"); + expect(fixture.nativeElement.querySelectorAll(".ui-udf-parameter-row.header .field-cell.dimmed")).toHaveLength(0); + }); + + it("offers no eye for a column the form marked as not hideable, and keeps the mark across a populate", () => { + const row = authoredRow(true, false); + const field = { + model, + props: { operatorID: "op-form" }, + fieldArray: () => row, + fieldGroup: [row], + } as FormlyFieldConfig; + populate(field); + fixture.detectChanges(); + expect(headerBoxes()).toHaveLength(3); + expect(headerEyes()).toHaveLength(0); + + // A second populate (every change re-runs it) finds the mark already there and keeps it, + // along with the accessible name the host gave the cell. + populate(field); + expect(row.fieldGroup![0].props?.["labelHosted"]).toBe(true); + expect(row.fieldGroup![0].props?.["schemaLabel"]).toBe("Value"); + }); + + it("keeps a plain text header for a reader's card and on the operator property panel", () => { + // A reader's rows carry no controls (authoring is off), so the header is the column's name, + // from what the form published for the card, and no cell is told otherwise. + const readerRow = row(); + const field = { + model, + props: { operatorID: "op-form", subFieldView: renamedAndHidden }, + fieldArray: () => readerRow, + fieldGroup: [readerRow], + } as FormlyFieldConfig; + populate(field); + fixture.detectChanges(); + expect(headerBoxes()).toHaveLength(0); + expect(headers()).toEqual(["Value", "Parameter"]); + expect(readerRow.fieldGroup![0].props?.["labelHosted"]).toBeUndefined(); + + // The panel: the same rows, no operator mark, so nothing is hosted and nothing is marked. + const panelRow = authoredRow(); + const panel = { model, fieldArray: () => panelRow, fieldGroup: [panelRow] } as FormlyFieldConfig; + populate(panel); + fixture.detectChanges(); + expect(headerBoxes()).toHaveLength(0); + expect(headers()).toEqual(["Value", "Name", "Type"]); + expect(panelRow.fieldGroup![0].props?.["labelHosted"]).toBeUndefined(); + }); + + it("shows a renamed column under its new name and leaves a hidden one out, in the header and the cells", () => { + // formly clones the template into the rows, so a row carries what the walk put on the template. + const field = { + model, + props: { operatorID: "op-form", subFieldView: renamedAndHidden }, + fieldArray: row(), + fieldGroup: [], + } as FormlyFieldConfig; + expect(populate(field)).toEqual(["Value", "Parameter"]); + + fixture.detectChanges(); + expect(headers()).toEqual(["Value", "Parameter"]); + expect(fixture.nativeElement.querySelectorAll(".ui-udf-parameter-row:not(.header) .field-cell")).toHaveLength(2); + }); + + // The draft row names and types the parameter being added, so it draws all three cells. With a + // column hidden, a filtered header left the name box under the wrong heading (Copilot on #8846). + it("shows the three fixed columns while the draft row is open, so its cells line up with the header", () => { + const field = { + model, + props: { operatorID: "op-form", subFieldView: renamedAndHidden }, + fieldArray: row(), + fieldGroup: [], + } as FormlyFieldConfig; + expect(populate(field)).toEqual(["Value", "Parameter"]); + + component.draftVisible = true; + fixture.detectChanges(); + + expect(headers()).toEqual(["Value", "Parameter", "Type"]); + const cellsIn = (selector: string) => fixture.nativeElement.querySelectorAll(selector).length; + expect(cellsIn(".ui-udf-parameter-row.draft .field-cell")).toBe(3); + expect(cellsIn(".ui-udf-parameter-row:not(.header):not(.draft) .field-cell")).toBe(3); + + // Closing the draft gives the author's hide back. + component.draftVisible = false; + fixture.detectChanges(); + expect(headers()).toEqual(["Value", "Parameter"]); + }); + + it("reads the first row when formly builds the rows on demand", () => { + const field = { + model, + props: { operatorID: "op-form", subFieldView: renamedAndHidden }, + fieldArray: () => row(), + fieldGroup: [], + } as FormlyFieldConfig; + expect(populate(field)).toEqual(["Value", "Parameter"]); + }); + + it("leaves a column out when the group it sits in is hidden, not only when it is itself", () => { + // Hiding the group is one decision the author made about the group, so that is the path the + // form publishes; what sits inside it goes with it. + const field = { + model, + props: { + operatorID: "op-form", + subFieldView: { value: { label: "Value", shown: true }, attribute: { label: "Attribute", shown: false } }, + }, + fieldArray: () => row(), + fieldGroup: [], + } as FormlyFieldConfig; + expect(populate(field)).toEqual(["Value"]); + }); + + it("shows the author's name for a column while it is being renamed, and follows the typing", () => { + // The form writes a name being typed into the very object it published, so the header follows + // without a rebuild (see onSubFieldNamed). + const view = { + value: { label: "Value", shown: true }, + "attribute.attributeName": { label: "Parameter (draft)", shown: true }, + "attribute.attributeType": { label: "Type", shown: false }, + }; + const field = { + model, + props: { operatorID: "op-form", subFieldView: view }, + fieldArray: () => row(), + fieldGroup: [], + } as FormlyFieldConfig; + expect(populate(field)).toEqual(["Value", "Parameter (draft)"]); + + view["attribute.attributeName"] = { label: "Threshold", shown: true }; + fixture.detectChanges(); + expect(headers()).toEqual(["Value", "Threshold"]); + }); + + // The old reading -- what formly left on the first built row -- had nothing to read before a row + // existed, so a table whose UDF declares nothing yet showed the un-overridden header. + it("answers for a table whose UDF declares no parameters yet, which has no rows to read", () => { + const field = { + model: [], + props: { operatorID: "op-form", subFieldView: renamedAndHidden }, + fieldArray: () => row(), + fieldGroup: [], + } as FormlyFieldConfig; + expect(populate(field)).toEqual(["Value", "Parameter"]); + }); + + it("keeps the fixed headers on the operator property panel, whatever the sub-fields carry", () => { + const field = { model, fieldArray: row(), fieldGroup: [] } as FormlyFieldConfig; + expect(populate(field)).toEqual(["Value", "Name", "Type"]); + }); + + it("keeps the panel's fixed header for a column the author did not rename, whatever the schema calls it", () => { + // formly puts the schema's own title on every sub-field's label; the panel never shows it, so + // neither does the form: only the author's name (authorName) replaces a fixed header. + const field = { + model, + props: { operatorID: "op-form" }, + fieldArray: { + fieldGroup: [ + { key: "value", props: { label: "Value" } }, + { + key: "attribute", + fieldGroup: [ + { key: "attributeName", props: { label: "Attribute Name" } }, + { key: "attributeType", props: { label: "Attribute Type" } }, + ], + }, + ], + }, + fieldGroup: [], + } as FormlyFieldConfig; + expect(populate(field)).toEqual(["Value", "Name", "Type"]); + }); + + it("reads the columns live, so a hide the author makes after populate takes the column out", () => { + const view: Record<string, { label: string; shown: boolean }> = { + value: { label: "Value", shown: true }, + "attribute.attributeName": { label: "Parameter", shown: true }, + "attribute.attributeType": { label: "Type", shown: true }, + }; + const field = { + model, + props: { operatorID: "op-form", subFieldView: view }, + fieldArray: row(), + fieldGroup: [], + } as FormlyFieldConfig; + expect(populate(field)).toEqual(["Value", "Parameter", "Type"]); + + view["attribute.attributeType"] = { label: "Type", shown: false }; + + expect(component.columns.map(column => component.columnLabel(column))).toEqual(["Value", "Parameter"]); + }); + + it("hands back the same column list while nothing changed, so the header does not redraw on every check", () => { + const field = { + model, + props: { operatorID: "op-form", subFieldView: renamedAndHidden }, + fieldArray: row(), + fieldGroup: [], + } as FormlyFieldConfig; + populate(field); + + const first = component.columns; + expect(component.columns).toBe(first); + }); + + it("locks the value cells of a read-only reader's card", () => { + // The Form View marks a reader's field props.disabled; the widget's own "the value is editable" + // used to re-enable the control after formly had disabled it. + const value = new FormControl("42"); + const row = rowConfig([{ key: "value", formControl: value }, { key: "attributeName" }, { key: "attributeType" }]); + const field = { + model, + props: { operatorID: "op-form", disabled: true }, + fieldArray: () => row, + fieldGroup: [row], + } as FormlyFieldConfig; + + component.onPopulate(field); + + expect(value.disabled).toBe(true); + }); + + // The rule itself -- a writer's card offers it without the canvas's flag, a reader's does not, + // nor does a writer's while a run is in flight -- is pinned under real formly in + // ui-udf-parameters.component.formly.spec.ts; here, what the widget does with it. + it("adds to the card's operator on a writer's card, without the canvas's flag", () => { + // Nothing is highlighted on the form (or another step is), so the field's own operator is the + // one the declaration goes into; the highlighted operator is the panel's rule only. And the + // flag is off outside edit mode, where a writer's card is still editable. + workflowActionServiceMock.checkWorkflowModificationEnabled.mockReturnValue(false); + (component as any).field = { + model: [], + fieldGroup: [], + props: { operatorID: "op-form" }, + formControl: new FormGroup({}), + }; + fixture.detectChanges(); + expect(component.editable).toBe(true); + expect(fixture.nativeElement.querySelector(".add-parameter-button")).not.toBeNull(); + + component.draftVisible = true; + component.addParameter({ value: "threshold" } as HTMLInputElement, "double"); + + expect(syncServiceMock.addParameter).toHaveBeenCalledWith("op-form", "threshold", "double"); + expect(component.draftVisible).toBe(false); + }); + + // Adding a parameter writes a declaration into the UDF's code, straight into the shared + // document, and the property panel and the canvas code editor both refuse a code edit while a + // run is in flight. The form's own lock cannot say so: it is held off outside edit mode for a + // different reason, so the card asks the execute service (meng). The check sits in the method, + // not only on the button, and the draft stays open. + it("adds nothing on a card that is not editable, whoever calls: a reader's, or a writer's while a run is in flight", () => { + const control = new FormGroup({}); + control.disable(); + (component as any).field = { + model: [], + fieldGroup: [], + props: { operatorID: "op-form", disabled: true }, + formControl: control, + }; + fixture.detectChanges(); + expect(component.editable).toBe(false); + expect(fixture.nativeElement.querySelector(".add-parameter-button")).toBeNull(); + component.draftVisible = true; + component.addParameter({ value: "threshold" } as HTMLInputElement, "double"); + expect(syncServiceMock.addParameter).not.toHaveBeenCalled(); + expect(component.draftVisible).toBe(true); + + executeServiceMock.isExecutionInFlight.mockReturnValue(true); + (component as any).field = { + model: [], + fieldGroup: [], + props: { operatorID: "op-form" }, + formControl: new FormGroup({}), + }; + fixture.detectChanges(); + expect(component.editable).toBe(false); + expect(fixture.nativeElement.querySelector(".add-parameter-button")).toBeNull(); + component.addParameter({ value: "threshold" } as HTMLInputElement, "double"); + expect(syncServiceMock.addParameter).not.toHaveBeenCalled(); + }); + }); + + it("adds nothing while the workflow may not be modified, whoever calls", () => { + workflowActionServiceMock.checkWorkflowModificationEnabled.mockReturnValue(false); + component.draftVisible = true; + + component.addParameter({ value: "threshold" } as HTMLInputElement, "double"); + + expect(syncServiceMock.addParameter).not.toHaveBeenCalled(); + expect(component.draftVisible).toBe(true); + }); + it("should add a parameter for the highlighted operator and close the draft row", () => { component.draftVisible = true; @@ -336,6 +794,15 @@ describe("UiUdfParametersComponent", () => { expect(notificationServiceMock.error).not.toHaveBeenCalled(); }); + it("adds to the highlighted operator as well before formly has handed the widget its field", () => { + (component as any).field = undefined; + component.draftVisible = true; + + component.addParameter({ value: "threshold" } as HTMLInputElement, "double"); + + expect(syncServiceMock.addParameter).toHaveBeenCalledWith(operatorId, "threshold", "double"); + }); + it("should surface edit errors and keep the draft row open", () => { component.draftVisible = true; syncServiceMock.addParameter.mockImplementation(() => { @@ -626,7 +1093,7 @@ describe("UiUdfParametersComponent", () => { fixture.detectChanges(); - expect(component.workflowModificationEnabled).toBe(false); + expect(component.editable).toBe(false); // Offering "Add parameter" on a read-only or running workflow would push a code edit // through the sync service onto a graph that must not be modified. expect(query(".add-parameter-button")).toBeNull(); diff --git a/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.ts b/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.ts index 952c923d06..e59d5c72d7 100644 --- a/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.ts +++ b/frontend/src/app/workspace/component/ui-udf-parameters/ui-udf-parameters.component.ts @@ -31,13 +31,28 @@ import { UiUdfParametersParseError, } from "../../service/code-editor/ui-udf-parameters-parser.service"; import { UiUdfParametersSyncService } from "../../service/code-editor/ui-udf-parameters-sync.service"; +import { ExecuteWorkflowService } from "../../service/execute-workflow/execute-workflow.service"; import { DATASET_INPUT_TYPE, MODEL_INPUT_TYPE } from "../../service/code-editor/ui-udf-parameters-parser.service"; import { UI_PARAMETER_TYPES } from "../../service/code-editor/ui-udf-parameter"; import type { AttributeType } from "../../types/workflow-compiling.interface"; +import { fieldOperatorID, renderedInFormView, renderedReadOnly } from "../../util/custom-formly-type"; +import { subFieldLabel, subFieldsInView } from "../../../common/formly/sub-field-view"; +import { EditableLabelWrapperComponent } from "../../../common/formly/editable-label-wrapper/editable-label-wrapper.component"; -type UiUdfParameterColumn = Readonly<{ label: string; key: string; parentKey?: string; disabled: boolean }>; +/** + * A column of the table. `path` is the column's sub-field path in the row, which is also the path + * the Form View's author names and hides it under -- the two are the same thing, so the column can + * be looked up in what the form published (see sub-field-view). + */ +type UiUdfParameterColumn = Readonly<{ + label: string; + key: string; + parentKey?: string; + path: string; + disabled: boolean; +}>; -const VALUE_COLUMN: UiUdfParameterColumn = { label: "Value", key: "value", disabled: false }; +const VALUE_COLUMN: UiUdfParameterColumn = { label: "Value", key: "value", path: "value", disabled: false }; const RESOURCE_VALUE_EDITOR = "resourcevalue"; const RESOURCE_INPUT_TYPES: ReadonlySet<string> = new Set([MODEL_INPUT_TYPE, DATASET_INPUT_TYPE]); @@ -69,28 +84,82 @@ export class UiUdfParametersComponent extends FieldArrayType<FormlyFieldConfig> readonly fieldColumns: UiUdfParameterColumn[] = [ VALUE_COLUMN, - { label: "Name", key: "attributeName", parentKey: "attribute", disabled: true }, - { label: "Type", key: "attributeType", parentKey: "attribute", disabled: true }, + { label: "Name", key: "attributeName", parentKey: "attribute", path: "attribute.attributeName", disabled: true }, + { label: "Type", key: "attributeType", parentKey: "attribute", path: "attribute.attributeType", disabled: true }, ]; + /** + * The columns in view: all three on the operator property panel, and on a Form View card the ones + * the author left (subFieldsInView, which keeps the array's identity so the header's ngFor does + * not redraw). All three come back while the draft row is open: that row names and types the + * parameter being added, so it needs them whatever the author hid, and a filtered header over its + * three cells put the name box under the wrong heading (Copilot on #8846). + * + * Read live rather than fixed at populate: the form publishes its decisions on the field, which + * this widget is handed after its first check. + */ + get columns(): readonly UiUdfParameterColumn[] { + return this.draftVisible ? this.fieldColumns : subFieldsInView(this.field ?? {}, this.fieldColumns); + } + readonly addParameterTypeOptions = UI_PARAMETER_TYPES; draftVisible = false; constructor( private workflowActionService: WorkflowActionService, private uiUdfParametersSyncService: UiUdfParametersSyncService, - private notificationService: NotificationService + private notificationService: NotificationService, + private executeWorkflowService: ExecuteWorkflowService ) { super(); } - get workflowModificationEnabled(): boolean { - return this.workflowActionService.checkWorkflowModificationEnabled(); + /** Whether this is a Form View card rather than the operator property panel; see editable. */ + get onFormView(): boolean { + return renderedInFormView(this.field ?? {}); } - /** Inserts the declaration into shared UDF code; the row then appears through the normal code sync. */ + /** + * Whether the table takes a new parameter here. On the operator property panel that is the + * canvas's rule, as it always was: the workflow may be modified (write access, no run in flight). + * + * A Form View card asks those two halves separately, because the canvas's flag does not answer + * either one there. Write access: the card is not a reader's, which the form marks on the field + * itself (props.disabled, its one lock on a card; see renderedReadOnly). A writer's card is + * editable in and out of edit mode, as every value on it is (adding a parameter is adding a row), + * and the flag is not that -- the Form View holds it off outside edit mode, against structural + * edits through its page, which hid the button on a card whose values could still be edited. No + * run in flight: asked of the execute service, which owns that rule, since the flag that would + * otherwise carry it is held off for the reason above. Adding a parameter inserts a declaration + * into the UDF's own code, straight into the shared document, and code is what a run must not have + * rewritten under it -- the property panel and the canvas code editor both refuse it then. + * + * The mark decides rather than the table's own control, which does not answer the question: + * formly disables the leaf controls under a disabled field, not the array itself, so a reader's + * table with no parameters yet reads as enabled (a reader's table with rows reads as disabled only + * because every row's controls are). + */ + get editable(): boolean { + if (!this.onFormView) { + return this.workflowActionService.checkWorkflowModificationEnabled(); + } + return !renderedReadOnly(this.field) && !this.executeWorkflowService.isExecutionInFlight(); + } + + /** + * Inserts the declaration into the operator's Python code; the row then appears through the normal + * code sync. The operator is the one the field is bound to on a Form View card (nothing is + * highlighted there, or another step is); on the operator property panel it is the highlighted one, + * as it always was. + */ addParameter(nameInput: HTMLInputElement, attributeType: string): void { - const operatorId = this.workflowActionService.getJointGraphWrapper().getCurrentHighlightedOperatorIDs()[0]; + // The button is hidden then too; the check belongs with the edit, not only with the button. + if (!this.editable) { + return; + } + const operatorId = + fieldOperatorID(this.field ?? {}) ?? + this.workflowActionService.getJointGraphWrapper().getCurrentHighlightedOperatorIDs()[0]; try { this.uiUdfParametersSyncService.addParameter(operatorId, nameInput.value, attributeType as AttributeType); this.draftVisible = false; @@ -105,7 +174,79 @@ export class UiUdfParametersComponent extends FieldArrayType<FormlyFieldConfig> this.dropRowsWhoseResourceChanged(field, this.parameterRows(field)); super.onPopulate(field); const rows = this.parameterRows(field); - field.fieldGroup?.forEach((rowField, index) => this.configureRowFields(rowField, rows[index]?.inputType)); + // A reader's card arrives with props.disabled on the field (the Form View's lock); the value + // column's "editable" below must not undo it. + const locked = field.props?.disabled === true; + field.fieldGroup?.forEach((rowField, index) => this.configureRowFields(rowField, rows[index]?.inputType, locked)); + this.hostColumnLabels(field); + } + + /** + * While authoring on the Form View, a column's name box and eye live in this table's header, not + * in its cells. The form's label wrapper decorates every row's sub-fields (the first row with the + * controls, later rows with a static name); drawn in the cells, under a header that already shows + * the name, that was the same name three times over. So whenever the header hosts a column's + * controls (columnControls), every cell of that column tells its wrapper the label is drawn here. + */ + private hostColumnLabels(field: FormlyFieldConfig): void { + for (const column of this.fieldColumns) { + if (!this.firstRowControls(field, column)) continue; + field.fieldGroup?.forEach(rowField => { + const cell = this.getColumnField(rowField, column); + if (!cell) return; + cell.props = { + ...cell.props, + [EditableLabelWrapperComponent.LABEL_HOSTED_PROP]: true, + // The control's accessible name falls back to this; the heading sighted readers see is the + // column's own label, so the two say the same thing ("Type", not "Attribute Type"). + schemaLabel: column.label, + }; + }); + } + } + + /** + * The props the header's controls for a column are bound to: the first row's sub-field, the row + * the form gave the controls to -- only on the Form View, and only while it did (`authoring`), so + * the panel's header and a reader's stay plain text. + */ + columnControls(column: UiUdfParameterColumn): FormlyFieldConfig["props"] | undefined { + return this.firstRowControls(this.field ?? {}, column); + } + + private firstRowControls( + field: FormlyFieldConfig, + column: UiUdfParameterColumn + ): FormlyFieldConfig["props"] | undefined { + const first = field.fieldGroup?.[0]; + if (!first || !renderedInFormView(field)) return undefined; + const props = this.getColumnField(first, column)?.props; + return props?.["authoring"] === true ? props : undefined; + } + + /** The header's name box: the wrapper's own write-through, on the first row's props. */ + renameColumn(column: UiUdfParameterColumn, event: Event): void { + const props = this.columnControls(column); + if (props) EditableLabelWrapperComponent.rename(props, (event.target as HTMLInputElement).value); + } + + /** The header's eye: the wrapper's own write-through, on the first row's props. */ + toggleColumnHidden(column: UiUdfParameterColumn): void { + const props = this.columnControls(column); + if (props) EditableLabelWrapperComponent.setHidden(props, !props["authorHidden"]); + } + + /** Whether the author hid this column: its cells fade through their wrappers, the header with them. */ + columnHidden(column: UiUdfParameterColumn): boolean { + return this.columnControls(column)?.["authorHidden"] === true; + } + + /** + * A column's header: the author's name for it on a Form View card, the fixed label otherwise -- + * not the schema's own title, which the operator property panel does not show either. + */ + columnLabel(column: UiUdfParameterColumn): string { + return subFieldLabel(this.field ?? {}, column.path, column.label); } /** @@ -132,8 +273,8 @@ export class UiUdfParametersComponent extends FieldArrayType<FormlyFieldConfig> this.configureRowColumns(rowField, this.setDisabledMetadata.bind(this)); } - private configureRowFields(rowField: FormlyFieldConfig | undefined, inputType?: string): void { - this.configureRowColumns(rowField, this.configureDisabledState.bind(this)); + private configureRowFields(rowField: FormlyFieldConfig | undefined, inputType?: string, locked = false): void { + this.configureRowColumns(rowField, (field, disabled) => this.configureDisabledState(field, disabled || locked)); this.configureValueEditor(rowField, inputType); } diff --git a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts index bd74299136..4290618345 100644 --- a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts +++ b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts @@ -72,7 +72,8 @@ describe("WorkflowFormComponent", () => { h.panelResizeService as any, h.validationWorkflowService as any, h.config as any, - h.warehouseService as any + h.warehouseService as any, + h.uiUdfParametersSyncService as any ); return component; }; @@ -905,6 +906,200 @@ describe("WorkflowFormComponent", () => { expect(component.rendered[0].fields[0].key).toBe(component.rendered[0].resolved.binding.id); }); + // The operator an input belongs to rides on its field: a shared widget that needs it (the + // ui-udf-parameters renderer, adding a declared parameter to the operator's code) reads it + // there, since nothing is highlighted on the form; the same mark tells it which host it is on. + it("marks every field with the operator it belongs to", () => { + build(formViewWorkflow).ngOnInit(); + + renderOne("n_hvg"); + + const card = component.rendered[0]; + expect((card.fields[0].props as any).operatorID).toBe(card.resolved.binding.operatorID); + }); + + // A Python UDF's code declares its UI parameters; the parser announces them and the step + // panel's frame writes them for the operator it shows live. A parameter added from a card + // changes the code with the panel closed or on another step, so the form is the writer then. + describe("UI parameters a Python UDF's code declares", () => { + const declared = [{ attribute: { attributeName: "n", attributeType: "integer" }, value: "3" }]; + const announce = () => h.uiParametersChanged.next({ operatorId: "op-1", parameters: declared }); + + /** Render one card for an operator's `uiParameters`, the card the declaration shows up on. */ + const renderParameterCard = (operatorID = "op-1", value: unknown = "seed") => { + h.formlyJsonschema.toFieldConfig = () => ({ + fieldGroup: [{ key: "uiParameters", props: { label: "Parameters" } }], + }); + h.hasOperatorIds.add(operatorID); + formBindingService.resolveFields.mockReturnValue([ + resolved("uiParameters", "Parameters", { + binding: { id: "uiParameters", operatorID, propertyKey: "uiParameters", displayName: "Parameters" }, + value, + }), + ]); + (component as any).readConfig(); + }; + + beforeEach(() => { + h.hasOperatorIds.add("op-1"); + h.graphOperators.push({ + operatorID: "op-1", + operatorType: "PythonUDFV2", + operatorProperties: { code: "x", uiParameters: [] }, + }); + h.graphOperators.push({ + operatorID: "op-2", + operatorType: "PythonUDFV2", + operatorProperties: { code: "y", uiParameters: [] }, + }); + }); + + it("writes them onto the operator for a writer, when the step panel is not editing that step", () => { + build(formViewWorkflow).ngOnInit(); + + announce(); + + expect(h.workflowActionService.setOperatorProperty).toHaveBeenCalledWith("op-1", { + code: "x", + uiParameters: declared, + }); + }); + + it("writes them when the panel shows that step read-only, since the frame does not then", () => { + build(formViewWorkflow).ngOnInit(); + component.selectedOperatorId = "op-1"; + vi.spyOn(component, "panelLive", "get").mockReturnValue(false); + + announce(); + + expect(h.workflowActionService.setOperatorProperty).toHaveBeenCalledTimes(1); + }); + + it("writes nothing for a reader", () => { + build({ ...formViewWorkflow, readonly: true }).ngOnInit(); + + announce(); + + expect(h.workflowActionService.setOperatorProperty).not.toHaveBeenCalled(); + }); + + it("writes nothing for an operator that is gone", () => { + build(formViewWorkflow).ngOnInit(); + h.hasOperatorIds.delete("op-1"); + + announce(); + + expect(h.workflowActionService.setOperatorProperty).not.toHaveBeenCalled(); + }); + + // The card showing the parameters would otherwise keep its old rows until the compilation + // result rebuilds it, and a value typed into it meanwhile would go back with the old rows, + // dropping the one just declared. The rebuild waits for the tick to end: the step panel's + // frame, subscribed after this page, writes after this page's handler has run. + it("rebuilds the cards after the current tick once the parameters are written, when a card shows that step's parameters", () => { + vi.useFakeTimers(); + build(formViewWorkflow).ngOnInit(); + renderParameterCard(); + expect(component.rendered).toHaveLength(1); + const order: string[] = []; + h.uiParametersChanged.subscribe(() => order.push("frame wrote")); + const readConfig = vi.spyOn(component as any, "readConfig").mockImplementation(() => order.push("rebuilt")); + + announce(); + expect(order).toEqual(["frame wrote"]); + vi.runAllTimers(); + + expect(order).toEqual(["frame wrote", "rebuilt"]); + expect(readConfig).toHaveBeenCalledTimes(1); + vi.useRealTimers(); + }); + + // What the rebuild is for: it goes through buildForm, which announces on formsRebuilt -- that + // cuts off the cards built with the old rows, whose write-back would otherwise put them back + // -- and the card ends up holding the declared rows, so a value typed into it next writes + // them back rather than the list it was built with. + it("rebuilds through buildForm, so the old cards are cut off and the card holds the newly declared rows", () => { + vi.useFakeTimers(); + build(formViewWorkflow).ngOnInit(); + renderParameterCard(); + expect(component.rendered[0].model["uiParameters"]).toBe("seed"); + const cutOff = vi.fn(); + (component as any).formsRebuilt.subscribe(cutOff); + // The operator now has the declared rows, so this is what the next resolve reads back. + formBindingService.resolveFields.mockReturnValue([ + resolved("uiParameters", "Parameters", { + binding: { id: "uiParameters", operatorID: "op-1", propertyKey: "uiParameters", displayName: "Parameters" }, + value: declared, + }), + ]); + + announce(); + vi.runAllTimers(); + + expect(cutOff).toHaveBeenCalled(); + expect(component.rendered[0].model["uiParameters"]).toEqual(declared); + vi.useRealTimers(); + }); + + // The frame is the writer for the step it shows live (the same write twice is churn), and the + // card still has to follow the rows the frame wrote. + it("leaves the write to the step panel's frame while it shows that step live, and still rebuilds the card", () => { + vi.useFakeTimers(); + build(formViewWorkflow).ngOnInit(); + renderParameterCard(); + component.selectedOperatorId = "op-1"; + vi.spyOn(component, "panelLive", "get").mockReturnValue(true); + const readConfig = vi.spyOn(component as any, "readConfig"); + + announce(); + vi.runAllTimers(); + + expect(h.workflowActionService.setOperatorProperty).not.toHaveBeenCalled(); + expect(readConfig).toHaveBeenCalledTimes(1); + vi.useRealTimers(); + }); + + // Held while the reader is typing, like every other rebuild here: a half-entered value under + // the cursor is not thrown away, and the hold is given back when the focus leaves. + it("holds the rebuild while the reader is typing, and runs it once the focus leaves", () => { + vi.useFakeTimers(); + build(formViewWorkflow).ngOnInit(); + renderParameterCard(); + const typing = vi.spyOn(component as any, "isTypingInTheForm").mockReturnValue(true); + const readConfig = vi.spyOn(component as any, "readConfig"); + + announce(); + vi.runAllTimers(); + expect(readConfig).not.toHaveBeenCalled(); + + typing.mockReturnValue(false); + component.onFocusOut(); + vi.runAllTimers(); + + expect(readConfig).toHaveBeenCalledTimes(1); + vi.useRealTimers(); + }); + + it("leaves the cards alone when none shows that step's parameters: another input, or another step's", () => { + vi.useFakeTimers(); + build(formViewWorkflow).ngOnInit(); + renderOne("n_hvg"); + const readConfig = vi.spyOn(component as any, "readConfig"); + + announce(); + vi.runAllTimers(); + expect(readConfig).not.toHaveBeenCalled(); + + renderParameterCard("op-2"); + expect(component.rendered).toHaveLength(1); + readConfig.mockClear(); + announce(); + vi.runAllTimers(); + expect(readConfig).not.toHaveBeenCalled(); + vi.useRealTimers(); + }); + }); + it("renders nothing for an input whose operator is no longer on the graph", () => { build(formViewWorkflow).ngOnInit(); // op-1 deliberately not added to the graph. @@ -1233,6 +1428,9 @@ describe("WorkflowFormComponent", () => { const sub = field.fieldGroup[0]; expect(sub.key).toBe("sub"); expect(sub.props.label).toBe("Renamed sub"); + // Published on the input's own field as well, for a widget that draws its own headers rather + // than going through formly's wrapper (ui-udf-parameters); see sub-field-view. + expect(field.props.subFieldView.sub).toEqual({ label: "Renamed sub", shown: false }); expect(sub.hide).toBe(true); // Hidden must not strip the value: formly's resetFieldOnHide default would otherwise clear it // from the model on render, and the card writes the whole nested object back -- deleting the @@ -1240,6 +1438,101 @@ describe("WorkflowFormComponent", () => { expect(sub.resetOnHide).toBe(false); }); + it("renames a sub-field that formly built without any props", () => { + build(formViewWorkflow).ngOnInit(); + h.formlyJsonschema.toFieldConfig = () => ({ + fieldGroup: [{ key: "nested", fieldGroup: [{ key: "sub" }] }], + }); + + const field = expose({ + id: "n", + operatorID: "op-1", + propertyKey: "nested", + displayName: "Nested", + overrides: { sub: { displayName: "Renamed sub" } }, + }); + + const sub = field.fieldGroup[0]; + expect(sub.props.label).toBe("Renamed sub"); + expect(field.props.subFieldView.sub).toEqual({ label: "Renamed sub", shown: true }); + }); + + // The name box writes into the published view so a widget drawing its own headers follows the + // typing. A wrapper left over from before a rebuild names a path the current view has never + // heard of; it must not plant an entry no walk produced. + it("ignores a rename for a sub-field path the published view does not carry", () => { + build(formViewWorkflow).ngOnInit(); + const field = expose({ + id: "n", + operatorID: "op-1", + propertyKey: "nested", + displayName: "Nested", + overrides: { sub: { displayName: "Renamed sub" } }, + }); + + expect(() => (component as any).onSubFieldNamed("n", "gone", "Whatever")).not.toThrow(); + + expect(field.props.subFieldView.gone).toBeUndefined(); + expect(field.props.subFieldView.sub).toEqual({ label: "Renamed sub", shown: true }); + }); + + // The name box writes on every keystroke, into the object the field already carries, so a widget + // drawing its own headers follows the typing without the rebuild a rename deliberately avoids. + it("writes a name being typed into the published view, on the field itself", () => { + build(formViewWorkflow).ngOnInit(); + const field = expose({ + id: "n", + operatorID: "op-1", + propertyKey: "nested", + displayName: "Nested", + overrides: { sub: { displayName: "Renamed sub" } }, + }); + const published = field.props.subFieldView; + + (component as any).onSubFieldNamed("n", "sub", "Threshold"); + + expect(published.sub).toEqual({ label: "Threshold", shown: true }); + expect(field.props.subFieldView).toBe(published); + + // Emptied, the override goes; the widget falls back to the name it would have drawn itself. + (component as any).onSubFieldNamed("n", "sub", ""); + expect(published.sub.label).toBe(""); + }); + + // An author keeps a hidden sub-field on screen, to bring it back; only a reader loses sight of + // it. A widget drawing its own headers has to be told the same thing. + it("tells an author a hidden sub-field is still in view, and a reader that it is not", () => { + build(formViewWorkflow).ngOnInit(); + const binding = { + id: "n", + operatorID: "op-1", + propertyKey: "nested", + displayName: "Nested", + overrides: { sub: { hidden: true } }, + }; + + expect(expose(binding).props.subFieldView.sub.shown).toBe(false); + + component.authoring = true; + expect(expose(binding).props.subFieldView.sub.shown).toBe(true); + }); + + // Only the author's name is published. A widget drawing its own chrome has a heading of its own + // for the part (the parameter table's "Type"), which it keeps rather than printing the schema's. + it("publishes no name for a sub-field the author did not rename", () => { + build(formViewWorkflow).ngOnInit(); + + const field = expose({ + id: "n", + operatorID: "op-1", + propertyKey: "nested", + displayName: "Nested", + overrides: { sub: { hidden: true } }, + }); + + expect(field.props.subFieldView.sub).toEqual({ label: "", shown: false }); + }); + it("renames and hides an overridden sub-field of a repeated section, per row", () => { build(formViewWorkflow).ngOnInit(); diff --git a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts index 4c493ec71d..d964284d0a 100644 --- a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts +++ b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts @@ -37,6 +37,7 @@ import { catchError, concatMap, debounceTime, finalize, observeOn, takeUntil, ta import { CdkDragDrop, DragDropModule } from "@angular/cdk/drag-drop"; import { isLeavingWorkspace, USER_WORKFLOW, workspaceCanvasUrl } from "../../../app-routing.constant"; import { EditableLabelWrapperComponent } from "../../../common/formly/editable-label-wrapper/editable-label-wrapper.component"; +import { SUB_FIELD_VIEW_PROP, SubFieldView } from "../../../common/formly/sub-field-view"; import { FormFieldBinding, Workflow, WorkflowContent } from "../../../common/type/workflow"; import { ComputingUnitStatusService } from "../../../common/service/computing-unit/computing-unit-status/computing-unit-status.service"; import { ComputingUnitState } from "../../../common/type/computing-unit-connection.interface"; @@ -46,7 +47,9 @@ import { WorkflowPersistService } from "../../../common/service/workflow-persist import { NotificationService } from "../../../common/service/notification/notification.service"; import { UserService } from "../../../common/service/user/user.service"; import { DynamicSchemaService } from "../../service/dynamic-schema/dynamic-schema.service"; -import { customFormlyFieldType, CANVAS_ONLY_FORMLY_TYPES } from "../../util/custom-formly-type"; +import { customFormlyFieldType, CANVAS_ONLY_FORMLY_TYPES, FIELD_OPERATOR_ID_PROP } from "../../util/custom-formly-type"; +import { UiUdfParametersSyncService } from "../../service/code-editor/ui-udf-parameters-sync.service"; +import type { UiUdfParameter } from "../../service/code-editor/ui-udf-parameters-parser.service"; import { WorkflowCompilingService } from "../../service/compile-workflow/workflow-compiling.service"; import { ExecuteWorkflowService, FORM_DEBOUNCE_TIME_MS } from "../../service/execute-workflow/execute-workflow.service"; import { OperatorMetadataService } from "../../service/operator-metadata/operator-metadata.service"; @@ -323,7 +326,8 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { // disabled here exactly when it is disabled there. private validationWorkflowService: ValidationWorkflowService, private config: GuiConfigService, - private warehouseService: WarehouseService + private warehouseService: WarehouseService, + private uiUdfParametersSyncService: UiUdfParametersSyncService ) {} ngOnInit(): void { @@ -515,6 +519,18 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { .pipe(debounceTime(FORM_DEBOUNCE_TIME_MS), untilDestroyed(this)) .subscribe(() => this.onCompilationChanged()); + // A Python UDF's code declares its UI parameters (`self.UiParameter(...)`); the parser announces + // them when the code changes, and the operator property panel's frame writes them onto the + // operator -- for the operator it shows, and only while it acts as the editor. A parameter added + // from a Form View card (the ui-udf-parameters widget's Add parameter) changes the code with the + // panel closed or on another step, so the form writes them then; see writeUiParameters. + this.uiUdfParametersSyncService.uiParametersChanged$ + .pipe(untilDestroyed(this)) + .subscribe(({ operatorId, parameters }) => { + this.writeUiParameters(operatorId, parameters); + this.followUiParameters(operatorId); + }); + // Exposing or un-exposing a property in the panel changes the definition; the inputs above have // to follow at once, which is the whole point of editing them side by side. Today this fires for // this client's own edits; once #8351 moves formBinding into the shared model it also fires for @@ -960,6 +976,46 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { ); } + /** + * Write the UI parameters a Python UDF's code declares onto the operator, as the operator + * property panel's frame does for the operator it shows while it acts as the editor. The frame + * does that only then, so the form writes when the frame does not: a writer only (a reader's card + * changes no code, and may not write), not while the step panel shows that very step live (the + * frame writes then, and the same write twice is churn), and only for an operator still on the + * graph. The same value the frame writes: the operator's properties with the declared list. + */ + private writeUiParameters(operatorId: string, parameters: UiUdfParameter[]): void { + const graph = this.workflowActionService.getTexeraGraph(); + const frameWrites = this.selectedOperatorId === operatorId && this.panelLive; + if (!this.canEdit || frameWrites || !graph.hasOperator(operatorId)) { + return; + } + this.workflowActionService.setOperatorProperty(operatorId, { + ...cloneDeep(graph.getOperator(operatorId).operatorProperties), + uiParameters: cloneDeep(parameters), + }); + } + + /** + * Once the declared parameters are written -- by writeUiParameters, or by the step panel's frame + * for the step it shows live, whose subscription runs after this page's -- the operator has the new + * rows while this page's card for them still shows the old ones: a card is rebuilt from the + * compilation result, half a second and a round trip later. A value typed into the card in that + * window would have gone back with the old rows (the card writes its whole list), dropping the row + * just declared. So the cards are rebuilt right after the current tick, once every writer has + * written, when a card shows that operator's parameters; held while the reader is typing, as every + * rebuild is. The compilation result rebuilds them once more, to the same rows. + */ + private followUiParameters(operatorId: string): void { + const shown = this.rendered.some( + card => card.resolved.binding.operatorID === operatorId && card.resolved.binding.propertyKey === "uiParameters" + ); + if (!shown) { + return; + } + this.later(() => this.rebuildFormOrDefer(true), 0); + } + private renderField(resolved: ResolvedField): RenderedField | undefined { const { binding } = resolved; // A broken input (its operator gone) has no schema to build a field from. Only an author ever @@ -1016,6 +1072,12 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { field.props = { ...(field.props ?? {}), label: binding.displayName || schemaLabel, + // The operator the input belongs to rides on the field: nothing is highlighted on the form, so + // a shared widget that needs its operator (the ui-udf-parameters renderer, adding a declared + // parameter to the operator's code) reads it here, and the same mark tells it which host it is + // on where the two must differ (its columns follow the author's overrides here, and keep their + // fixed headers on the panel). + [FIELD_OPERATOR_ID_PROP]: binding.operatorID, }; const form = new FormGroup({}); @@ -1138,6 +1200,9 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { } } const controlsAt = new Set<string>(); + /** Published on the input's own field once the walk has seen every path; see sub-field-view. */ + const subFieldView: Record<string, SubFieldView> = {}; + this.subFieldViewByBinding.set(binding.id, subFieldView); const walk = (node: FormlyFieldConfig, path: string, root: boolean): void => { // Drop the schema's own description on every field, nested ones included: on this page the // one piece of guidance is the help text the form's author writes, rendered once by the card. @@ -1184,8 +1249,20 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { // placeholder and tooltip, and what clearing the box yields, since an empty name deletes the // override (setFieldOverride). const schemaOwnLabel = (node.props?.label as string) || path; + // What a widget that draws its own chrome has to show for this sub-field, resolved here + // where the author's decision is, rather than left for the widget to read back out of the + // fields below (see sub-field-view). The first node met for a path answers for it, as it + // does for the controls: the rows of a repeated section share one override. + subFieldView[path] ??= { + // The author's name only. A widget drawing its own chrome has a name of its own for the + // part and uses it when the author kept the schema's -- the table's "Type" heading, which + // the operator property panel shows too, rather than the schema's "Attribute Type". + label: override.displayName ?? "", + // An author keeps a hidden sub-field on screen, to bring it back; a reader does not see it. + shown: this.authoring || override.hidden !== true, + }; if (override.displayName) { - node.props = { ...(node.props ?? {}), label: override.displayName }; + node.props = { ...node.props, label: override.displayName }; } if (this.authoring) { // An author edits the sub-field's label where it appears and keeps hidden fields on @@ -1270,8 +1347,18 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { } }; walk(field, "", true); + // On the input's own field, where a widget drawing its own chrome reads it. Written after the + // walk so it carries every path, including the ones a repeated section's builder adds. + // The walk set props on the root before anything else, so there is always an object here. + field.props = { ...field.props, [SUB_FIELD_VIEW_PROP]: subFieldView }; } + /** + * The sub-field view published on each input's field, kept here so a rename being typed can be + * written into the very object the field carries (see onSubFieldNamed and sub-field-view). + */ + private readonly subFieldViewByBinding = new Map<string, Record<string, SubFieldView>>(); + /** Followers are kept per input and path; "/" cannot occur in a binding id (a uuid). */ private static followerKey(bindingId: string, path: string): string { return bindingId + "/" + path; @@ -1708,6 +1795,13 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { for (const node of this.followersByPath.get(WorkflowFormComponent.followerKey(bindingId, path)) ?? []) { node.props = { ...(node.props ?? {}), authorName: value }; } + // And the published view, for a widget drawing its own headers: the same object the field + // carries, so the header follows the typing without a rebuild. An emptied box deletes the + // override, and the widget falls back to its own name (subFieldLabel). + const view = this.subFieldViewByBinding.get(bindingId)?.[path]; + if (view !== undefined) { + this.subFieldViewByBinding.get(bindingId)![path] = { ...view, label: value }; + } } private onSubFieldHiddenAt(bindingId: string, path: string, hidden: boolean): void { diff --git a/frontend/src/app/workspace/component/workflow-form/workflow-form.rendered.spec.ts b/frontend/src/app/workspace/component/workflow-form/workflow-form.rendered.spec.ts index 7437037ce8..2bd7b9880b 100644 --- a/frontend/src/app/workspace/component/workflow-form/workflow-form.rendered.spec.ts +++ b/frontend/src/app/workspace/component/workflow-form/workflow-form.rendered.spec.ts @@ -52,6 +52,7 @@ import { OperatorMetadataService } from "../../service/operator-metadata/operato import { FormBindingService } from "../../service/form-binding/form-binding.service"; import { DynamicSchemaService } from "../../service/dynamic-schema/dynamic-schema.service"; import { WorkflowCompilingService } from "../../service/compile-workflow/workflow-compiling.service"; +import { UiUdfParametersSyncService } from "../../service/code-editor/ui-udf-parameters-sync.service"; import { ExecuteWorkflowService } from "../../service/execute-workflow/execute-workflow.service"; import { WorkflowResultService } from "../../service/workflow-result/workflow-result.service"; import { NotificationService } from "../../../common/service/notification/notification.service"; @@ -219,6 +220,7 @@ describe("WorkflowFormComponent (rendered template)", () => { provide: WorkflowCompilingService, useValue: { getCompilationStateInfoChangedStream: () => EMPTY }, }, + { provide: UiUdfParametersSyncService, useValue: { uiParametersChanged$: EMPTY } }, { provide: ExecuteWorkflowService, useValue: { diff --git a/frontend/src/app/workspace/component/workflow-form/workflow-form.spec-harness.ts b/frontend/src/app/workspace/component/workflow-form/workflow-form.spec-harness.ts index 95c3eecd07..8767626962 100644 --- a/frontend/src/app/workspace/component/workflow-form/workflow-form.spec-harness.ts +++ b/frontend/src/app/workspace/component/workflow-form/workflow-form.spec-harness.ts @@ -157,7 +157,11 @@ export function setupHarness() { // The heat-map overlay's view; reset by the views on leaving the workspace, kept on a hand-over. setHeatmapView: vi.fn(), }; + // The parser's announcement of the UI parameters a Python UDF's code declares. + const uiParametersChanged = new Subject<{ operatorId: string; parameters: unknown[] }>(); + const uiUdfParametersSyncService = { uiParametersChanged$: uiParametersChanged.asObservable() }; const workflowActionService = { + setOperatorProperty: vi.fn(), resetAsNewWorkflow: vi.fn(), setNewSharedModel: vi.fn(), reloadWorkflow: vi.fn(), @@ -401,6 +405,8 @@ export function setupHarness() { computingUnitStatusService, workflowConsoleService, workflowWebsocketService, + uiUdfParametersSyncService, + uiParametersChanged, panelResizeService, validationWorkflowService, host, diff --git a/frontend/src/app/workspace/service/execute-workflow/execute-workflow.service.spec.ts b/frontend/src/app/workspace/service/execute-workflow/execute-workflow.service.spec.ts index 906dcd6fe4..8f71b16741 100644 --- a/frontend/src/app/workspace/service/execute-workflow/execute-workflow.service.spec.ts +++ b/frontend/src/app/workspace/service/execute-workflow/execute-workflow.service.spec.ts @@ -374,6 +374,37 @@ describe("ExecuteWorkflowService", () => { }); }); + // A caller that must refuse a structural edit mid-run asks here rather than re-listing the states, + // and a view whose own lock no longer means "a run is on" -- the Form View clamps it off outside + // edit mode -- has nowhere else honest to ask. + describe("isExecutionInFlight", () => { + it("answers for each state exactly as the graph lock does", () => { + const actionService = service["workflowActionService"]; + const disable = vi.spyOn(actionService, "disableWorkflowModification"); + + expect(service.isExecutionInFlight()).toBe(false); // Uninitialized + + for (const state of [ + ExecutionState.Initializing, + ExecutionState.Running, + ExecutionState.Pausing, + ExecutionState.Paused, + ExecutionState.Resuming, + ExecutionState.Recovering, + ]) { + disable.mockClear(); + emitWsEvent({ type: "WorkflowStateEvent", state }); + expect(service.isExecutionInFlight(), state).toBe(true); + expect(disable, state).toHaveBeenCalled(); + } + + for (const state of [ExecutionState.Completed, ExecutionState.Failed, ExecutionState.Killed]) { + emitWsEvent({ type: "WorkflowStateEvent", state }); + expect(service.isExecutionInFlight(), state).toBe(false); + } + }); + }); + it("resetExecutionAndWorkers() clears the execution state and worker assignments", () => { (service as any).currentState = { state: ExecutionState.Running }; (service as any).assignedWorkerIds.set("op1", ["w1", "w2"]); diff --git a/frontend/src/app/workspace/service/execute-workflow/execute-workflow.service.ts b/frontend/src/app/workspace/service/execute-workflow/execute-workflow.service.ts index 6ef22669e5..8ead716b69 100644 --- a/frontend/src/app/workspace/service/execute-workflow/execute-workflow.service.ts +++ b/frontend/src/app/workspace/service/execute-workflow/execute-workflow.service.ts @@ -507,7 +507,13 @@ export class ExecuteWorkflowService { this.anchorDuration(0, false); } - private isExecutionInFlight(state: ExecutionState): boolean { + /** + * Whether a run is in flight, which is what locks the graph. Public and defaulted to the current + * state for a caller that must refuse a structural edit mid-run and has nowhere else honest to + * ask: a view whose own lock no longer means "a run is on" (the Form View clamps it off outside + * edit mode) cannot read it off that flag. + */ + public isExecutionInFlight(state: ExecutionState = this.currentState.state): boolean { switch (state) { case ExecutionState.Initializing: case ExecutionState.Running: diff --git a/frontend/src/app/workspace/util/custom-formly-type.spec.ts b/frontend/src/app/workspace/util/custom-formly-type.spec.ts index 3f3de31c6e..cabf7fc228 100644 --- a/frontend/src/app/workspace/util/custom-formly-type.spec.ts +++ b/frontend/src/app/workspace/util/custom-formly-type.spec.ts @@ -17,7 +17,14 @@ * under the License. */ -import { customFormlyFieldType, NON_FORM_FIELD_TYPES, CANVAS_ONLY_FORMLY_TYPES } from "./custom-formly-type"; +import { + customFormlyFieldType, + NON_FORM_FIELD_TYPES, + CANVAS_ONLY_FORMLY_TYPES, + fieldOperatorID, + renderedInFormView, + renderedReadOnly, +} from "./custom-formly-type"; describe("NON_FORM_FIELD_TYPES", () => { it("blocks only the code editor from being a form field, not the drag-reorder list", () => { @@ -37,6 +44,34 @@ describe("CANVAS_ONLY_FORMLY_TYPES", () => { }); }); +describe("fieldOperatorID", () => { + it("is the operator the Form View bound the field to, and nothing for a panel field", () => { + expect(fieldOperatorID({ props: { operatorID: "op-1" } })).toBe("op-1"); + expect(fieldOperatorID({ props: { operatorID: "" } })).toBeUndefined(); + expect(fieldOperatorID({ props: { operatorID: 7 } })).toBeUndefined(); + expect(fieldOperatorID({ props: {} })).toBeUndefined(); + expect(fieldOperatorID({})).toBeUndefined(); + }); +}); + +describe("renderedInFormView", () => { + it("is true only for a field the Form View marked with its operator", () => { + expect(renderedInFormView({ props: { operatorID: "op-1" } })).toBe(true); + expect(renderedInFormView({ props: { operatorID: "" } })).toBe(false); + expect(renderedInFormView({ props: {} })).toBe(false); + expect(renderedInFormView({})).toBe(false); + }); +}); + +describe("renderedReadOnly", () => { + it("is true only for a field the Form View marked disabled, a reader's", () => { + expect(renderedReadOnly({ props: { disabled: true } })).toBe(true); + expect(renderedReadOnly({ props: { disabled: false } })).toBe(false); + expect(renderedReadOnly({ props: {} })).toBe(false); + expect(renderedReadOnly({})).toBe(false); + }); +}); + describe("customFormlyFieldType", () => { it("maps a fileName property to the autocomplete input", () => { expect(customFormlyFieldType({ key: "fileName", operatorType: "CSVFileScan" })).toBe("inputautocomplete"); diff --git a/frontend/src/app/workspace/util/custom-formly-type.ts b/frontend/src/app/workspace/util/custom-formly-type.ts index df9766afd3..33d40fe7b5 100644 --- a/frontend/src/app/workspace/util/custom-formly-type.ts +++ b/frontend/src/app/workspace/util/custom-formly-type.ts @@ -34,6 +34,39 @@ export const NON_FORM_FIELD_TYPES: ReadonlySet<string> = new Set(["codearea"]); */ export const CANVAS_ONLY_FORMLY_TYPES: ReadonlySet<string> = new Set(["codearea"]); +/** + * The operator an exposed field belongs to, which the Form View sets in `props` on every field it + * renders. A shared widget that needs its operator reads it from here on the form, where nothing is + * highlighted: the ui-udf-parameters renderer adds a declared parameter to that operator's code. On + * the operator property panel, whose fields exist because of the highlight, the highlighted operator + * is the one, and no field carries this. So it also tells a widget which host it is on, where the two + * must differ: the same renderer keeps its fixed column headers on the panel and derives them from the + * author's renames and hides on the form (#8763). + */ +export const FIELD_OPERATOR_ID_PROP = "operatorID"; + +/** The operator the Form View bound a field to, if it rendered the field; see {@link FIELD_OPERATOR_ID_PROP}. */ +export function fieldOperatorID(field: { props?: Record<string, unknown> }): string | undefined { + const id = field.props?.[FIELD_OPERATOR_ID_PROP]; + return typeof id === "string" && id !== "" ? id : undefined; +} + +/** Whether a field is being rendered by the Form View (see {@link FIELD_OPERATOR_ID_PROP}). */ +export function renderedInFormView(field: { props?: Record<string, unknown> }): boolean { + return fieldOperatorID(field) !== undefined; +} + +/** + * Whether the Form View rendered a field for a reader, who may not change the workflow: it marks the + * field `props.disabled`, the one lock it puts on a card, and formly disables the controls it builds + * under such a field. A widget with a button of its own (ui-udf-parameters' Add parameter) reads the + * mark here rather than its control: formly disables controls, not arrays, so an array with no rows + * reads as enabled. + */ +export function renderedReadOnly(field: { props?: Record<string, unknown> }): boolean { + return field.props?.["disabled"] === true; +} + /** * The custom formly widget an operator-schema property renders as, decided from the property key * and its operator. A single source of truth extracted from the operator property panel so that a
