You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@causeway.apache.org by da...@apache.org on 2026/08/24 21:11:04 UTC
(causeway) 14/15: adds paged GraphQL reference autocomplete
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit a50a842c00a187e9b71b08743d76d5e0685b23fd
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 21:55:16 2026 +0100
adds paged GraphQL reference autocomplete
---
.../core/config/CausewayConfiguration.java | 27 ++++
.../evidence/REPRODUCING.md | 62 ++++++++
.../evidence/final-gate-results.md | 33 ++++
.../evidence/implementation-report.md | 40 +++++
.../evidence/production-isolation.md | 19 +++
.../evidence/window-shape-matrix.md | 46 ++++++
.../tasks.md | 156 +++++++++----------
.../htmx/src/main/resources/application.properties | 4 +-
.../htmx/ReferenceAppHtmxPlaywrightTest.java | 58 +++++--
.../ReferenceAppCapabilityInventory_IntegTest.java | 3 +-
.../ReferenceAppHtmxApplication_IntegTest.java | 124 +++++++++++++++
.../inventory/ReferenceAppCapabilityInventory.java | 7 +
.../referenceapp/referenceapp-targets.json | 1 +
.../ROOT/pages/setup-and-configuration.adoc | 12 ++
.../viewer/graphql/model/domain/TypeNames.java | 14 ++
.../rich/query/AutoCompleteWindowOrdering.java | 23 +++
.../domain/rich/query/RichActionParamsParam.java | 8 +
.../RichActionParamsParamAutoCompleteWindow.java | 83 ++++++++++
.../domain/rich/query/RichAutoCompleteWindow.java | 167 +++++++++++++++++++++
.../model/domain/rich/query/RichProperty.java | 8 +
.../rich/query/RichPropertyAutoCompleteWindow.java | 68 +++++++++
.../InvalidAutoCompleteWindowException.java | 26 ++++
.../model/registry/GraphQLTypeRegistry.java | 20 +--
.../query/AutoCompleteWindowConfigurationTest.java | 40 +++++
.../registry/GraphQLTypeRegistryUnionTest.java | 12 ++
viewers/webcomponents/foundation/USAGE.adoc | 8 +-
.../foundation/src/editor-registry.mjs | 5 +-
.../foundation/src/graphql-client.mjs | 4 +-
.../src/interaction-controller-element.mjs | 92 +++++++++---
.../foundation/src/interaction-operations.mjs | 68 +++++++++
.../foundation/src/object-context-controller.mjs | 90 ++++++++++-
.../foundation/src/property-element.mjs | 77 ++++++++--
.../foundation/src/reference-widget.mjs | 62 +++++++-
.../foundation/src/service-action-context.mjs | 62 +++++++-
.../test/application-menu-client.test.mjs | 17 +++
.../test/fixtures/menu-graphql-fixture.mjs | 27 +++-
.../test/fixtures/rich-schema-fixture.mjs | 47 ++++++
.../foundation/test/graphql-client.test.mjs | 20 +++
.../foundation/test/interaction-command.test.mjs | 109 ++++++++++++++
.../foundation/test/interaction.test.mjs | 128 ++++++++++++++++
viewers/webcomponents/htmx/README.adoc | 3 +-
.../petclinic/PetClinicHtmxPlaywrightTest.java | 10 +-
42 files changed, 1744 insertions(+), 146 deletions(-)
diff --git a/core/config/src/main/java/org/apache/causeway/core/config/CausewayConfiguration.java b/core/config/src/main/java/org/apache/causeway/core/config/CausewayConfiguration.java
index 6cb2c9b3f83..2065b1cbb04 100644
--- a/core/config/src/main/java/org/apache/causeway/core/config/CausewayConfiguration.java
+++ b/core/config/src/main/java/org/apache/causeway/core/config/CausewayConfiguration.java
@@ -2388,6 +2388,8 @@ public record Graphql(
@DefaultValue
Collections collections,
@DefaultValue
+ Autocomplete autocomplete,
+ @DefaultValue
Resources resources,
@DefaultValue
Authentication authentication
@@ -2645,6 +2647,31 @@ public record Collections(
}
}
+ /**
+ * Controls bounded rich GraphQL autocomplete response windows.
+ */
+ public record Autocomplete(
+ /**
+ * Default item count used when an autocomplete window omits its size.
+ */
+ @Min(value = 1)
+ @DefaultValue("20")
+ int defaultWindowSize,
+ /**
+ * Hard maximum item count accepted for one autocomplete window.
+ */
+ @Min(value = 1)
+ @DefaultValue("100")
+ int maxWindowSize) {
+
+ public Autocomplete {
+ if (defaultWindowSize > maxWindowSize) {
+ throw new IllegalArgumentException(
+ "causeway.viewer.graphql.autocomplete.default-window-size must not exceed max-window-size");
+ }
+ }
+ }
+
/**
* The different ways in which resources ({@link org.apache.causeway.applib.value.Blob} bytes,
* {@link org.apache.causeway.applib.value.Clob} chars, grids and icons) are made available.
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/REPRODUCING.md b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/REPRODUCING.md
new file mode 100644
index 00000000000..15ac69d8479
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/REPRODUCING.md
@@ -0,0 +1,62 @@
+# Reproducing paged reference autocomplete
+
+Use Temurin 25 for Maven commands.
+Install the changed core configuration, GraphQL model, and web-component artifacts before running the separate Reference Application reactor.
+
+## Configuration and GraphQL model
+
+```shell
+mvn -pl core/config -am test
+mvn -f viewers/graphql/pom.xml -pl model -am test
+mvn -f viewers/graphql/pom.xml -pl model -am -DskipTests install
+```
+
+The model suite covers configuration validation and existing schema behavior.
+The Reference Application integration below proves generated property-independent action-parameter fields, type metadata, all window boundaries, legacy compatibility, ordering, and non-disclosing errors against the real metamodel.
+
+## Foundation
+
+```shell
+cd viewers/webcomponents/foundation
+node --test
+cd ../../..
+mvn -f viewers/webcomponents/pom.xml -pl foundation,htmx -am test
+```
+
+Focused tests cover targeted window and item discovery, advertised selection, immutable normalization, property, object-action, and service-action execution, dependent arguments, legacy fallback, native search handling, Vaadin later-page callbacks, and stale-filter rejection.
+
+## Reference Application GraphQL
+
+```shell
+mvn -f viewers/webcomponents/pom.xml -pl foundation,htmx -am -DskipTests install
+mvn -f regressiontests/referenceapp/pom.xml \
+ -Dtest=ReferenceAppHtmxApplication_IntegTest#actionReferenceAutocompleteExposesBoundedServerWindowsAndLegacyCompatibility \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+```
+
+## Reference Application candidate and native browser modes
+
+```shell
+mvn -f regressiontests/referenceapp/pom.xml \
+ -Preferenceapp-playwright \
+ -Dtest=ReferenceAppHtmxPlaywrightTest#menusChoicesAutocompleteCancellationAndRouteDisposal \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+
+mvn -f regressiontests/referenceapp/pom.xml \
+ -Preferenceapp-playwright \
+ -Dtest=ReferenceAppHtmxPlaywrightTest#menusChoicesAutocompleteCancellationAndRouteDisposal \
+ -Dsurefire.failIfNoSpecifiedTests=false \
+ -Dcauseway.viewer.webcomponents.htmx.vaadin-reference-widgets=false test
+```
+
+## Full qualification
+
+```shell
+mvn -f viewers/webcomponents/pom.xml -pl sample-htmx-petclinic -am -Pplaywright test
+mvn -f regressiontests/referenceapp/pom.xml clean package
+mvn -f regressiontests/referenceapp/pom.xml -Preferenceapp-playwright \
+ -Dtest=ReferenceAppHtmxPlaywrightTest \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+openspec validate add-paged-graphql-reference-autocomplete --strict
+git diff --check
+```
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/final-gate-results.md b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/final-gate-results.md
new file mode 100644
index 00000000000..a653c5bcaf5
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/final-gate-results.md
@@ -0,0 +1,33 @@
+# Final gate results
+
+## Passed
+
+- Core configuration reactor and autocomplete validation tests: `BUILD SUCCESS`.
+- GraphQL model reactor, concurrent registry test, and existing model tests: `BUILD SUCCESS`.
+- Foundation Node suite: 154 tests passed with zero failures.
+- Web-component foundation and HTMX Maven reactor: `BUILD SUCCESS`.
+- Focused Reference Application window and legacy GraphQL integration: `BUILD SUCCESS`.
+- Petclinic candidate Playwright: 4 tests passed with zero failures, errors, or skips.
+- Petclinic explicit native Playwright: 4 tests passed with zero failures, errors, or skips.
+- Reference Application ordinary clean package, integration tests, inventory tests, and deterministic fixtures: `BUILD SUCCESS`.
+- Reference Application candidate Playwright: 9 tests passed with zero failures, errors, or skips.
+- Reference Application focused explicit native autocomplete journey: passed.
+- Clean and incremental capability inventory retained SHA-256 `75ef904a0d4fbc9c915c74866cdbd503743dab589f7525bbab126baf1eaa024a` byte-for-byte.
+- Vaadin production-like pilot: 5 scenarios with zero axe, CSP, console, page, external-request, or overflow failures.
+- Core configuration, GraphQL model, HTMX, and Reference Application RAT checks: `BUILD SUCCESS`.
+- Strict OpenSpec validation, `git diff --check`, and production-isolation review: passed.
+
+## Corrected executable outcomes
+
+Property and action-parameter wrappers retain legacy autocomplete and advertise bounded response windows.
+The Reference Application seven-result filter returns a five-item first page and two-item later page with accurate count and continuation metadata.
+The unchanged legacy list exactly matches concatenated window order.
+The internal Vaadin data provider selects an item absent from page zero and submits it through the existing action contract.
+Native mode obtains the first page, reports additional matches honestly, selects an authoritative reference, and submits without sending raw search text as an object input.
+Invalid windows are rejected without exposing the search value.
+
+## Retained limits and next step
+
+Each page request materializes one authoritative application autocomplete result before slicing; persistence query pushdown, cursors, and cross-request snapshots remain outside the public metamodel contract.
+The standalone foundation RAT goal still reports the same pre-existing `vaadin-reference/README.adoc` and generated `vaadin-reference.js` resources, neither introduced nor modified here.
+The next recommended change is `expand-vaadin-semantic-editor-families`.
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/implementation-report.md b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/implementation-report.md
new file mode 100644
index 00000000000..bd2d32f508e
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/implementation-report.md
@@ -0,0 +1,40 @@
+# Paged reference autocomplete implementation report
+
+## GraphQL model
+
+GraphQL configuration now supplies autocomplete default and maximum response-window sizes with validated defaults of 20 and 100.
+Rich properties and action parameters that already expose `autoComplete` additionally expose `autoCompleteWindow`.
+Existing field names, arguments, result types, and data fetchers remain unchanged.
+
+A shared server element validates offset and size, invokes the existing authorized Causeway autocomplete semantic once, copies application encounter order, and returns an immutable response slice with complete count and continuation metadata.
+Member-specific generated result types retain exact item output mapping.
+Object and service action parameters retain only advertised preceding arguments through the existing negotiation and conversion model.
+Errors are bounded and omit search text, pending arguments, identities, and values.
+GraphQL type registration is synchronized and returns snapshots so parallel metamodel discovery cannot lose a generated type while the additive window types are registered.
+
+## Semantic client
+
+Targeted introspection follows window, item, abstract/concrete, and metadata types.
+Object and service contexts add immutable window-returning methods while retaining every list-returning method.
+Window operations select only advertised arguments and fields.
+Servers without the additive field are normalized as marked legacy results and remain subject to the established complete-response bound.
+
+Filter changes, dependent argument changes, prompt closure, route replacement, disconnect, and request generations abort or reject stale work.
+Native autocomplete no longer submits raw search text as a domain-object pending value while the user is still filtering.
+It renders the bounded first window and an accessible refinement message when `hasNext` is true.
+
+## Internal Vaadin adapter
+
+Pinned Vaadin 25.2.8 documentation and package metadata confirm the lazy callback contract `dataProvider({filter, page, pageSize}, callback)` and `callback(items, totalSize)`.
+The internal Causeway adapter uses the introspected default page size, maps pages to semantic offset requests, normalizes rich object metadata to stable identities, and supplies authoritative total count.
+Outdated filter callbacks are ignored.
+Finite choices and legacy autocomplete retain the established items and fallback behavior.
+No Vaadin API crosses the public Causeway component boundary.
+
+## Reference Application
+
+The qualification page and maximum are five against an existing deterministic seven-result filter.
+The inventory normalizes the conditionally advertised abstract `ValueHolder.name` wrapper so clean and incremental schema traversals remain byte-identical without hiding a capability change.
+GraphQL covers first, later, defaulted, empty, invalid, and legacy operations.
+The candidate browser journey requests page one directly through the internal data provider and submits a reference absent from page zero.
+Native mode obtains the first window, exposes the refinement message, selects an authoritative item, and submits through the same action contract.
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/production-isolation.md b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/production-isolation.md
new file mode 100644
index 00000000000..ccc9531effa
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/production-isolation.md
@@ -0,0 +1,19 @@
+# Production isolation verification
+
+The change adds rich GraphQL fields and generated result types but removes or renames no existing field, argument, type, operation, route, semantic event, context method, or result kind.
+Legacy `autoComplete(search)` remains executable and unchanged.
+The server invokes the same Causeway property or parameter autocomplete semantic, authorization context, pending preceding arguments, and output mapper.
+
+No dependency, Maven coordinate, npm package, lock file, Vaadin version, generated Vaadin bundle, checksum, exact CSP hash, asset URL, CDN source, telemetry, Flow, Binder, Java DataProvider, Pro component, or application-facing Vaadin element changed.
+The JavaScript data-provider callback is contained within `<causeway-reference-editor>`.
+Causeway contexts continue to own GraphQL, pending values, identity, validation, cancellation, events, routes, and state.
+
+Candidate delivery remains route-lazy.
+Unqualified routes make zero Vaadin requests.
+Native fallback remains available through the existing viewer property and does not require the candidate bundle.
+`style-src-attr 'none'` and the four exact style hashes remain unchanged.
+
+The public window bounds browser transfer only.
+Documentation and diagnostics explicitly avoid claims of database query pushdown, cursor stability, or cross-request snapshots.
+Search text, protected pending arguments, identifiers, result values, and raw exception details are absent from evidence and bounded errors.
+Rollback returns new clients to legacy bounded autocomplete and requires no application, route, data, or asset migration.
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/window-shape-matrix.md b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/window-shape-matrix.md
new file mode 100644
index 00000000000..9ca5ade1323
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/window-shape-matrix.md
@@ -0,0 +1,46 @@
+# Autocomplete window shape matrix
+
+## Public GraphQL fields
+
+| Context | Existing field | Additive field |
+|---|---|---|
+| Rich property wrapper | `autoComplete(search): [Item]` | `autoCompleteWindow(search, offset = 0, size = configuredDefault): Window` |
+| Rich object-action parameter wrapper | Existing declared preceding arguments plus `search` | Same declared preceding arguments plus `search`, `offset`, and `size` |
+| Rich service-action parameter wrapper | Existing declared preceding arguments plus `search` | Same declared preceding arguments plus `search`, `offset`, and `size` |
+
+Every generated window contains `items`, `offset`, `requestedSize`, `returnedCount`, `totalCount`, `maximumSize`, `hasPrevious`, `hasNext`, and `ordering`.
+`items` uses the same advertised output type as legacy autocomplete.
+`ordering` is `APPLICATION`, meaning the authoritative application encounter order for that execution.
+No cursor, persistence query pushdown, or cross-request snapshot is claimed.
+
+## Bounds
+
+| Request | Result |
+|---|---|
+| Offset omitted | Uses zero. |
+| Size omitted | Uses `causeway.viewer.graphql.autocomplete.default-window-size`. |
+| Valid offset and size | Invokes domain autocomplete once and returns at most `size` items. |
+| Offset at or beyond total | Returns an empty successful window with accurate total and continuation metadata. |
+| Negative offset | Bounded error before domain invocation. |
+| Zero or negative size | Bounded error before domain invocation. |
+| Size above configured maximum | Bounded error before domain invocation. |
+
+Defaults are 20 items and a 100-item hard maximum.
+The Reference Application qualification overrides both values to five.
+
+## Safe deterministic Reference Application evidence
+
+The search text itself and returned identifiers are omitted from evidence.
+The approved one-character filter yields seven deterministic `TvCharacter` references in application encounter order.
+The first five-item window reports five items and `hasNext=true`.
+The second window at offset five reports two items, `hasPrevious=true`, and `hasNext=false`.
+The concatenated window identities exactly match the unchanged seven-item legacy result.
+An offset of 100 returns zero items and retains total count seven.
+
+## Client behavior
+
+Targeted introspection follows the generated window type, item type, concrete metadata type, defaults, and advertised scalar metadata.
+Object and service contexts return one immutable semantic shape and retain existing list-returning methods.
+Vaadin receives `{filter, page, pageSize}` and calls the semantic context with `offset = page * pageSize`; its callback receives normalized items and authoritative total count.
+Native presentation renders the first bounded window and states when more matches require refinement.
+Legacy-only servers retain the existing complete-response bound and visible over-bound failure.
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/tasks.md b/openspec/changes/add-paged-graphql-reference-autocomplete/tasks.md
index 7bc32dceb28..c1fbd651121 100644
--- a/openspec/changes/add-paged-graphql-reference-autocomplete/tasks.md
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/tasks.md
@@ -1,113 +1,113 @@
## 1. Establish current and target contracts
-- [ ] 1.1 Capture existing property and action-parameter autocomplete field shapes and legacy client limits.
-- [ ] 1.2 Record deterministic Reference Application autocomplete order, total, and configured qualification page size.
-- [ ] 1.3 Define property, object-action, service-action, scalar, enum, object, versionless, and polymorphic window shapes.
-- [ ] 1.4 Define valid, defaulted, boundary, empty, overflow, dependent-argument, and changing-result vectors.
+- [x] 1.1 Capture existing property and action-parameter autocomplete field shapes and legacy client limits.
+- [x] 1.2 Record deterministic Reference Application autocomplete order, total, and configured qualification page size.
+- [x] 1.3 Define property, object-action, service-action, scalar, enum, object, versionless, and polymorphic window shapes.
+- [x] 1.4 Define valid, defaulted, boundary, empty, overflow, dependent-argument, and changing-result vectors.
## 2. Add GraphQL configuration and window types
-- [ ] 2.1 Add GraphQL autocomplete default-window-size and max-window-size configuration with validated defaults.
-- [ ] 2.2 Add deterministic generated type names for property and action-parameter autocomplete windows.
-- [ ] 2.3 Add a dedicated bounded autocomplete-window exception that omits submitted values.
-- [ ] 2.4 Add the `APPLICATION` ordering enum and deduplicated registry construction.
-- [ ] 2.5 Build member-specific window result types with items and complete paging metadata.
-- [ ] 2.6 Validate offset and size before invoking domain autocomplete.
-- [ ] 2.7 Materialize one authoritative result per request, preserve encounter order, and return an immutable slice.
+- [x] 2.1 Add GraphQL autocomplete default-window-size and max-window-size configuration with validated defaults.
+- [x] 2.2 Add deterministic generated type names for property and action-parameter autocomplete windows.
+- [x] 2.3 Add a dedicated bounded autocomplete-window exception that omits submitted values.
+- [x] 2.4 Add the `APPLICATION` ordering enum and deduplicated registry construction.
+- [x] 2.5 Build member-specific window result types with items and complete paging metadata.
+- [x] 2.6 Validate offset and size before invoking domain autocomplete.
+- [x] 2.7 Materialize one authoritative result per request, preserve encounter order, and return an immutable slice.
## 3. Expose additive property windows
-- [ ] 3.1 Add `autoCompleteWindow` beside each advertised rich property `autoComplete` field.
-- [ ] 3.2 Preserve the existing property autocomplete field and data fetcher unchanged.
-- [ ] 3.3 Use the same source object, authorization, search text, item output mapping, and Causeway autocomplete semantic.
-- [ ] 3.4 Register the generated field, result type, item type, and data fetcher deterministically.
+- [x] 3.1 Add `autoCompleteWindow` beside each advertised rich property `autoComplete` field.
+- [x] 3.2 Preserve the existing property autocomplete field and data fetcher unchanged.
+- [x] 3.3 Use the same source object, authorization, search text, item output mapping, and Causeway autocomplete semantic.
+- [x] 3.4 Register the generated field, result type, item type, and data fetcher deterministically.
## 4. Expose additive action-parameter windows
-- [ ] 4.1 Add `autoCompleteWindow` beside each advertised rich action-parameter autocomplete field.
-- [ ] 4.2 Preserve preceding declared parameter arguments and append search, offset, and size.
-- [ ] 4.3 Reuse parameter negotiation, conversion, authorization, and item output mapping.
-- [ ] 4.4 Preserve existing object and service action autocomplete documents unchanged.
-- [ ] 4.5 Register action-parameter window result types and data fetchers deterministically.
+- [x] 4.1 Add `autoCompleteWindow` beside each advertised rich action-parameter autocomplete field.
+- [x] 4.2 Preserve preceding declared parameter arguments and append search, offset, and size.
+- [x] 4.3 Reuse parameter negotiation, conversion, authorization, and item output mapping.
+- [x] 4.4 Preserve existing object and service action autocomplete documents unchanged.
+- [x] 4.5 Register action-parameter window result types and data fetchers deterministically.
## 5. Add GraphQL model and integration verification
-- [ ] 5.1 Test autocomplete configuration defaults, valid overrides, and default-not-greater-than-maximum validation.
-- [ ] 5.2 Test deterministic result type naming and registry deduplication.
-- [ ] 5.3 Test valid first, middle, final, empty, exact-maximum, and defaulted windows.
-- [ ] 5.4 Test negative offset, zero size, and above-maximum requests fail before domain invocation.
-- [ ] 5.5 Test action dependent arguments remain declared and authoritative.
-- [ ] 5.6 Test legacy fields retain their previous schema and result behavior.
-- [ ] 5.7 Test item output mapping for object identity and supported non-object values.
+- [x] 5.1 Test autocomplete configuration defaults, valid overrides, and default-not-greater-than-maximum validation.
+- [x] 5.2 Test deterministic result type naming and registry deduplication.
+- [x] 5.3 Test valid first, middle, final, empty, exact-maximum, and defaulted windows.
+- [x] 5.4 Test negative offset, zero size, and above-maximum requests fail before domain invocation.
+- [x] 5.5 Test action dependent arguments remain declared and authoritative.
+- [x] 5.6 Test legacy fields retain their previous schema and result behavior.
+- [x] 5.7 Test item output mapping for object identity and supported non-object values.
## 6. Extend targeted client discovery and semantic contexts
-- [ ] 6.1 Follow advertised autocomplete-window result and item types through targeted introspection.
-- [ ] 6.2 Describe window defaults, maximum metadata fields, and item output shape without speculative selections.
-- [ ] 6.3 Add one immutable normalized semantic autocomplete-window result shape.
-- [ ] 6.4 Add object-context property window execution that emits only advertised arguments and fields.
-- [ ] 6.5 Add object-action parameter window execution with current preceding values.
-- [ ] 6.6 Add service-action parameter window execution with current preceding values.
-- [ ] 6.7 Preserve existing list-returning context methods for compatibility.
-- [ ] 6.8 Normalize legacy list fallback only within the existing accepted bound and mark it non-windowed.
-- [ ] 6.9 Add cancellation, request-key, filter-generation, and stale-response tests across overlapping pages.
+- [x] 6.1 Follow advertised autocomplete-window result and item types through targeted introspection.
+- [x] 6.2 Describe window defaults, maximum metadata fields, and item output shape without speculative selections.
+- [x] 6.3 Add one immutable normalized semantic autocomplete-window result shape.
+- [x] 6.4 Add object-context property window execution that emits only advertised arguments and fields.
+- [x] 6.5 Add object-action parameter window execution with current preceding values.
+- [x] 6.6 Add service-action parameter window execution with current preceding values.
+- [x] 6.7 Preserve existing list-returning context methods for compatibility.
+- [x] 6.8 Normalize legacy list fallback only within the existing accepted bound and mark it non-windowed.
+- [x] 6.9 Add cancellation, request-key, filter-generation, and stale-response tests across overlapping pages.
## 7. Integrate toolkit-neutral property and action controllers
-- [ ] 7.1 Prefer window capability for property searches and reset paging when filter text changes.
-- [ ] 7.2 Prefer window capability for object and service action parameter searches.
-- [ ] 7.3 Reset dependent parameter paging when preceding pending values change.
-- [ ] 7.4 Preserve pending value, semantic identity, validation, focus, cancellation, and prompt contracts.
-- [ ] 7.5 Expose an accessible additional-results or refine indication for native first-window presentation.
-- [ ] 7.6 Retain visible legacy over-bound failure without silent slicing.
-- [ ] 7.7 Add controller tests for later pages, out-of-order completion, supersession, prompt closure, route replacement, and disconnect.
+- [x] 7.1 Prefer window capability for property searches and reset paging when filter text changes.
+- [x] 7.2 Prefer window capability for object and service action parameter searches.
+- [x] 7.3 Reset dependent parameter paging when preceding pending values change.
+- [x] 7.4 Preserve pending value, semantic identity, validation, focus, cancellation, and prompt contracts.
+- [x] 7.5 Expose an accessible additional-results or refine indication for native first-window presentation.
+- [x] 7.6 Retain visible legacy over-bound failure without silent slicing.
+- [x] 7.7 Add controller tests for later pages, out-of-order completion, supersession, prompt closure, route replacement, and disconnect.
## 8. Connect the internal Vaadin lazy data provider
-- [ ] 8.1 Confirm current Vaadin Combo Box data-provider and callback semantics from pinned-version documentation.
-- [ ] 8.2 Add an internal page-request bridge carrying filter, offset, size, and a one-shot responder.
-- [ ] 8.3 Configure Combo Box page size and lazy data provider only when window capability is advertised.
-- [ ] 8.4 Return authoritative items and total count without assigning or slicing a complete local item array.
-- [ ] 8.5 Cancel or ignore stale provider callbacks after filter change, rerender, route replacement, or disconnect.
-- [ ] 8.6 Reconcile selected single and multi-reference identities even when their pages are not loaded.
-- [ ] 8.7 Preserve finite-items behavior and fallback for choices and legacy autocomplete.
-- [ ] 8.8 Add adapter tests for first and later pages, empty results, changed totals, stale callbacks, selection, and fallback.
+- [x] 8.1 Confirm current Vaadin Combo Box data-provider and callback semantics from pinned-version documentation.
+- [x] 8.2 Add an internal page-request bridge carrying filter, offset, size, and a one-shot responder.
+- [x] 8.3 Configure Combo Box page size and lazy data provider only when window capability is advertised.
+- [x] 8.4 Return authoritative items and total count without assigning or slicing a complete local item array.
+- [x] 8.5 Cancel or ignore stale provider callbacks after filter change, rerender, route replacement, or disconnect.
+- [x] 8.6 Reconcile selected single and multi-reference identities even when their pages are not loaded.
+- [x] 8.7 Preserve finite-items behavior and fallback for choices and legacy autocomplete.
+- [x] 8.8 Add adapter tests for first and later pages, empty results, changed totals, stale callbacks, selection, and fallback.
## 9. Qualify the pinned Reference Application
-- [ ] 9.1 Configure a deterministic qualification page smaller than the existing autocomplete result set.
-- [ ] 9.2 Add target-catalogue and inventory coverage for multi-window autocomplete.
-- [ ] 9.3 Verify property or action-parameter first, middle, final, and empty windows through real GraphQL.
-- [ ] 9.4 Verify counts, continuation, encounter order, requested maximum, and invalid-window errors.
-- [ ] 9.5 Verify legacy autocomplete still returns its established complete result.
-- [ ] 9.6 Add a browser journey that obtains and selects a reference absent from the first window.
-- [ ] 9.7 Verify dependent values, validation or submission, semantic identity, cancellation, and stale-filter behavior.
-- [ ] 9.8 Qualify native fallback and explicitly enabled Vaadin modes without external requests or policy regressions.
-- [ ] 9.9 Verify clean and incremental capability inventory generation remain byte-identical.
+- [x] 9.1 Configure a deterministic qualification page smaller than the existing autocomplete result set.
+- [x] 9.2 Add target-catalogue and inventory coverage for multi-window autocomplete.
+- [x] 9.3 Verify property or action-parameter first, middle, final, and empty windows through real GraphQL.
+- [x] 9.4 Verify counts, continuation, encounter order, requested maximum, and invalid-window errors.
+- [x] 9.5 Verify legacy autocomplete still returns its established complete result.
+- [x] 9.6 Add a browser journey that obtains and selects a reference absent from the first window.
+- [x] 9.7 Verify dependent values, validation or submission, semantic identity, cancellation, and stale-filter behavior.
+- [x] 9.8 Qualify native fallback and explicitly enabled Vaadin modes without external requests or policy regressions.
+- [x] 9.9 Verify clean and incremental capability inventory generation remain byte-identical.
## 10. Preserve compatibility and production isolation
-- [ ] 10.1 Verify no existing GraphQL field, route, component, semantic event, context result, or operation placement is removed or renamed.
-- [ ] 10.2 Verify no Flow, Binder, Java DataProvider, Pro component, telemetry, CDN, or application-facing Vaadin API is introduced.
-- [ ] 10.3 Verify unaffected routes remain route-lazy with zero Vaadin requests.
-- [ ] 10.4 Verify exact CSP hashes, `style-src-attr 'none'`, bundle checksum, native rollback, and package dependencies remain unchanged.
-- [ ] 10.5 Verify errors and evidence omit search text, protected pending arguments, identifiers, and returned values.
-- [ ] 10.6 Verify documentation does not claim database pushdown, cursor stability, or cross-request snapshots.
+- [x] 10.1 Verify no existing GraphQL field, route, component, semantic event, context result, or operation placement is removed or renamed.
+- [x] 10.2 Verify no Flow, Binder, Java DataProvider, Pro component, telemetry, CDN, or application-facing Vaadin API is introduced.
+- [x] 10.3 Verify unaffected routes remain route-lazy with zero Vaadin requests.
+- [x] 10.4 Verify exact CSP hashes, `style-src-attr 'none'`, bundle checksum, native rollback, and package dependencies remain unchanged.
+- [x] 10.5 Verify errors and evidence omit search text, protected pending arguments, identifiers, and returned values.
+- [x] 10.6 Verify documentation does not claim database pushdown, cursor stability, or cross-request snapshots.
## 11. Document the capability
-- [ ] 11.1 Update GraphQL setup documentation with fields, result metadata, configuration, ordering, and consistency limits.
-- [ ] 11.2 Update foundation and HTMX reference-editor documentation with window preference and legacy fallback.
-- [ ] 11.3 Add an operation-shape and window-bound matrix with safe Reference Application counts.
-- [ ] 11.4 Add reproducible focused and full qualification commands.
-- [ ] 11.5 Add implementation, compatibility, security, rollback, and retained-limit evidence.
-- [ ] 11.6 Record final gate results and the next recommended Vaadin editor-family change.
+- [x] 11.1 Update GraphQL setup documentation with fields, result metadata, configuration, ordering, and consistency limits.
+- [x] 11.2 Update foundation and HTMX reference-editor documentation with window preference and legacy fallback.
+- [x] 11.3 Add an operation-shape and window-bound matrix with safe Reference Application counts.
+- [x] 11.4 Add reproducible focused and full qualification commands.
+- [x] 11.5 Add implementation, compatibility, security, rollback, and retained-limit evidence.
+- [x] 11.6 Record final gate results and the next recommended Vaadin editor-family change.
## 12. Run final qualification gates
-- [ ] 12.1 Run GraphQL configuration, model, schema, and focused integration suites.
-- [ ] 12.2 Run foundation Node and web-component Maven suites.
-- [ ] 12.3 Run full Petclinic integration and Playwright suites in native and applicable candidate modes.
-- [ ] 12.4 Run Reference Application clean package, integration, inventory, and Playwright suites.
-- [ ] 12.5 Run strict CSP, accessibility, keyboard, responsive, theme, external-request, console-error, page-error, and overflow gates.
-- [ ] 12.6 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
+- [x] 12.1 Run GraphQL configuration, model, schema, and focused integration suites.
+- [x] 12.2 Run foundation Node and web-component Maven suites.
+- [x] 12.3 Run full Petclinic integration and Playwright suites in native and applicable candidate modes.
+- [x] 12.4 Run Reference Application clean package, integration, inventory, and Playwright suites.
+- [x] 12.5 Run strict CSP, accessibility, keyboard, responsive, theme, external-request, console-error, page-error, and overflow gates.
+- [x] 12.6 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
diff --git a/regressiontests/referenceapp/htmx/src/main/resources/application.properties b/regressiontests/referenceapp/htmx/src/main/resources/application.properties
index 96d35d96671..e3e18fd82ac 100644
--- a/regressiontests/referenceapp/htmx/src/main/resources/application.properties
+++ b/regressiontests/referenceapp/htmx/src/main/resources/application.properties
@@ -19,6 +19,8 @@ causeway.viewer.webcomponents.htmx.brand=Causeway Reference Application
causeway.viewer.webcomponents.htmx.wicket-comparison-path=/wicket/
causeway.viewer.webcomponents.htmx.application-stylesheet=/css/application.css
causeway.viewer.webcomponents.htmx.vaadin-reference-widgets=true
-causeway.viewer.webcomponents.htmx.reference-minimum-search-length=2
+causeway.viewer.webcomponents.htmx.reference-minimum-search-length=1
causeway.viewer.webcomponents.htmx.reference-maximum-results=50
+causeway.viewer.graphql.autocomplete.default-window-size=5
+causeway.viewer.graphql.autocomplete.max-window-size=5
causeway.value-types.kroki.backend-url=
diff --git a/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java b/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
index 7644561a53e..cbf3b64b5b4 100644
--- a/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
+++ b/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
@@ -131,7 +131,7 @@ void menusChoicesAutocompleteCancellationAndRouteDisposal() {
"demo_ActionAutoCompleteMenu", "autoComplete", "rich__demo_ActionAutoCompletePage"));
objectAction("selectTvCharacter").click();
waitForPrompt("selectTvCharacter");
- selectFirstAutocompleteChoice("tvCharacter", "Tom");
+ selectLaterAutocompleteChoice("tvCharacter", "o");
submitPrompt();
page.locator(PROMPT).waitFor(new Locator.WaitForOptions()
.setState(com.microsoft.playwright.options.WaitForSelectorState.DETACHED));
@@ -552,6 +552,11 @@ private void waitForPrompt(final String actionId) {
private void selectFirstAvailableChoice(final String parameterId) {
final Locator control = page.locator(parameter(parameterId));
+ if (Boolean.TRUE.equals(control.evaluate("element => element.localName === 'select'"))) {
+ control.evaluate("element => { element.selectedIndex = 0; "
+ + "element.dispatchEvent(new Event('change', {bubbles: true, composed: true})); }");
+ return;
+ }
try {
page.waitForFunction("selector => document.querySelector(selector)?.dataset.widgetState === 'ready'", parameter(parameterId));
} catch (com.microsoft.playwright.TimeoutError cause) {
@@ -567,16 +572,49 @@ private void selectFirstAvailableChoice(final String parameterId) {
page.waitForFunction("selector => document.querySelector(selector)?.value?.id", parameter(parameterId));
}
- private void selectFirstAutocompleteChoice(final String parameterId, final String search) {
+ private void selectLaterAutocompleteChoice(final String parameterId, final String search) {
final Locator control = page.locator(parameter(parameterId));
- final Locator input = control.locator("vaadin-combo-box input");
- input.fill(search);
- page.waitForFunction("selector => { const element = document.querySelector(selector); return element?.dataset.widgetState === 'ready' && element.querySelector('vaadin-combo-box')?.items?.length > 0; }", parameter(parameterId));
- final String label = (String) control.evaluate("element => element.querySelector('vaadin-combo-box').items[0].title");
- input.fill(label);
- input.focus();
- page.keyboard().press("ArrowDown");
- page.keyboard().press("Enter");
+ final Locator parameterContainer = page.locator("[data-parameter='" + parameterId + "']");
+ try {
+ page.waitForFunction("selector => { const editor = document.querySelector(selector); "
+ + "return editor?.matches('causeway-reference-editor, input[list]') "
+ + "|| editor?.querySelector('causeway-reference-editor, input[list]'); }", parameter(parameterId));
+ } catch (final com.microsoft.playwright.TimeoutError cause) {
+ throw new AssertionError("Autocomplete editor was unavailable: " + page.locator(PROMPT).innerHTML(), cause);
+ }
+ if (!Boolean.TRUE.equals(control.evaluate("element => element.localName === 'causeway-reference-editor'"))) {
+ final Locator input = control;
+ input.fill(search);
+ try {
+ page.waitForFunction("selector => document.querySelector(selector)?.querySelectorAll('datalist option').length > 0",
+ "[data-parameter='" + parameterId + "']");
+ } catch (final com.microsoft.playwright.TimeoutError cause) {
+ throw new AssertionError("Native autocomplete did not receive its first window: "
+ + page.locator(PROMPT).innerHTML(), cause);
+ }
+ assertThat(parameterContainer.locator(".causeway-autocomplete-continuation").innerText())
+ .containsIgnoringCase("more matches");
+ final String encoded = parameterContainer.locator("datalist option").first().getAttribute("value");
+ input.evaluate("(element, value) => { element.value = value; "
+ + "element.dispatchEvent(new Event('change', {bubbles: true, composed: true})); }", encoded);
+ page.waitForFunction("() => document.querySelector('[data-testid=action-prompt-submit]')?.disabled === false");
+ return;
+ }
+ control.locator("vaadin-combo-box").waitFor();
+ final JsonNode pageResult = OBJECT_MAPPER.valueToTree(control.evaluate("async (element, search) => {\n"
+ + " const combo = element.querySelector('vaadin-combo-box');\n"
+ + " if (typeof combo?.dataProvider !== 'function') throw new Error('Windowed data provider is unavailable');\n"
+ + " return await new Promise(resolve => combo.dataProvider(\n"
+ + " {filter: search, page: 1, pageSize: 5},\n"
+ + " (items, total) => {\n"
+ + " const selected = items[0];\n"
+ + " combo.dispatchEvent(new CustomEvent('selected-item-changed', {detail: {value: selected}}));\n"
+ + " resolve({count: items.length, total, selected, error: element.dataset.widgetError || null});\n"
+ + " }));\n"
+ + "}", search));
+ assertThat(pageResult.path("count").asInt()).as(pageResult.toPrettyString()).isGreaterThan(0);
+ assertThat(pageResult.path("total").asInt()).isGreaterThan(5);
+ assertThat(pageResult.at("/selected/id").asText()).isNotBlank();
page.waitForFunction("selector => document.querySelector(selector)?.value?.id", parameter(parameterId));
}
diff --git a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
index 6eec2ca7468..e0d74bbe7fd 100644
--- a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
+++ b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
@@ -107,7 +107,8 @@ private void assertJourneyTargetsExist(final JsonNode introspection) throws Exce
.contains(target.path("member").asText());
}
assertThat(families).contains(
- "action-choices", "action-autocomplete", "action-defaults", "action-validation",
+ "action-choices", "action-autocomplete", "reference-autocomplete-window",
+ "action-defaults", "action-validation",
"action-parameterless", "action-parameterized", "action-scalar-outcome",
"action-object-outcome", "action-cancel-stale-concurrency",
"versionless-preparation", "versionless-action-result", "versionless-collection-row",
diff --git a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
index 045b16b9758..09419f92cad 100644
--- a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
+++ b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
@@ -17,8 +17,10 @@
import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime;
import java.util.Base64;
+import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
+import java.util.stream.Stream;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -318,6 +320,128 @@ void polymorphicCollectionsCompleteUnionMembershipAndAcceptFragments() throws Ex
assertThat(first.at("/name/get").asText()).isNotBlank();
}
+ @Test
+ void actionReferenceAutocompleteExposesBoundedServerWindowsAndLegacyCompatibility() throws Exception {
+ final JsonNode opened = graphQL("""
+ mutation {
+ demo_ActionAutoCompleteMenu__autoComplete {
+ _meta { id logicalTypeName title }
+ }
+ }
+ """);
+ assertNoGraphQLErrors(opened);
+ final String pageId = opened.at("/data/demo_ActionAutoCompleteMenu__autoComplete/_meta/id").asText();
+ assertThat(pageId).isNotBlank();
+
+ final String target = "demo_ActionAutoCompletePage(object: {id: "
+ + OBJECT_MAPPER.writeValueAsString(pageId) + "})";
+ final JsonNode described = graphQL("""
+ { __type(name: "rich__demo_ActionAutoCompletePage__selectTvCharacter__tvCharacter__gqlv_action_parameter") {
+ fields { name args { name defaultValue } type { kind name ofType { kind name } } }
+ } }
+ """);
+ assertNoGraphQLErrors(described);
+ assertThat(described.at("/data/__type/fields").findValuesAsText("name"))
+ .contains("autoComplete", "autoCompleteWindow");
+ final JsonNode retainedLegacyType = graphQL("""
+ { __type(name: "rich__demo_ValueHolder__name__gqlv_property") { name } }
+ """);
+ assertNoGraphQLErrors(retainedLegacyType);
+ assertThat(retainedLegacyType.at("/data/__type/name").asText()).isNotBlank();
+
+ final JsonNode first = graphQL("""
+ { rich { %s { selectTvCharacter { params { tvCharacter {
+ autoCompleteWindow(search: "o", offset: 0, size: 5) {
+ items { _meta { id logicalTypeName title } }
+ offset requestedSize returnedCount totalCount maximumSize
+ hasPrevious hasNext ordering
+ }
+ } } } } } }
+ """.formatted(target));
+ assertNoGraphQLErrors(first);
+ final JsonNode firstWindow = first.at(
+ "/data/rich/demo_ActionAutoCompletePage/selectTvCharacter/params/tvCharacter/autoCompleteWindow");
+ assertThat(firstWindow.path("offset").asInt()).isZero();
+ assertThat(firstWindow.path("requestedSize").asInt()).isEqualTo(5);
+ assertThat(firstWindow.path("returnedCount").asInt()).isEqualTo(5);
+ assertThat(firstWindow.path("totalCount").asInt()).isEqualTo(7);
+ assertThat(firstWindow.path("maximumSize").asInt()).isEqualTo(5);
+ assertThat(firstWindow.path("hasPrevious").asBoolean()).isFalse();
+ assertThat(firstWindow.path("hasNext").asBoolean()).isTrue();
+ assertThat(firstWindow.path("ordering").asText()).isEqualTo("APPLICATION");
+
+ final JsonNode later = graphQL("""
+ { rich { %s { selectTvCharacter { params { tvCharacter {
+ autoCompleteWindow(search: "o", offset: 5, size: 5) {
+ items { _meta { id logicalTypeName title } }
+ offset returnedCount totalCount hasPrevious hasNext
+ }
+ } } } } } }
+ """.formatted(target));
+ assertNoGraphQLErrors(later);
+ final JsonNode laterWindow = later.at(
+ "/data/rich/demo_ActionAutoCompletePage/selectTvCharacter/params/tvCharacter/autoCompleteWindow");
+ assertThat(laterWindow.path("offset").asInt()).isEqualTo(5);
+ assertThat(laterWindow.path("returnedCount").asInt()).isGreaterThan(0);
+ assertThat(laterWindow.path("totalCount").asInt()).isEqualTo(firstWindow.path("totalCount").asInt());
+ assertThat(laterWindow.path("hasPrevious").asBoolean()).isTrue();
+ assertThat(firstWindow.at("/items").findValuesAsText("id"))
+ .doesNotContainAnyElementsOf(laterWindow.at("/items").findValuesAsText("id"));
+
+ final JsonNode boundaries = graphQL("""
+ { rich { %s { selectTvCharacter { params { tvCharacter {
+ defaulted: autoCompleteWindow(search: "o") {
+ offset requestedSize returnedCount totalCount
+ }
+ empty: autoCompleteWindow(search: "o", offset: 100, size: 5) {
+ items { _meta { id } } offset returnedCount totalCount hasPrevious hasNext
+ }
+ } } } } } }
+ """.formatted(target));
+ assertNoGraphQLErrors(boundaries);
+ final JsonNode defaulted = boundaries.at(
+ "/data/rich/demo_ActionAutoCompletePage/selectTvCharacter/params/tvCharacter/defaulted");
+ assertThat(defaulted.path("offset").asInt()).isZero();
+ assertThat(defaulted.path("requestedSize").asInt()).isEqualTo(5);
+ assertThat(defaulted.path("returnedCount").asInt()).isEqualTo(5);
+ final JsonNode empty = boundaries.at(
+ "/data/rich/demo_ActionAutoCompletePage/selectTvCharacter/params/tvCharacter/empty");
+ assertThat(empty.path("items").size()).isZero();
+ assertThat(empty.path("offset").asInt()).isEqualTo(100);
+ assertThat(empty.path("returnedCount").asInt()).isZero();
+ assertThat(empty.path("totalCount").asInt()).isEqualTo(firstWindow.path("totalCount").asInt());
+ assertThat(empty.path("hasPrevious").asBoolean()).isTrue();
+ assertThat(empty.path("hasNext").asBoolean()).isFalse();
+
+ final JsonNode legacy = graphQL("""
+ { rich { %s { selectTvCharacter { params { tvCharacter {
+ autoComplete(search: "o") { _meta { id logicalTypeName title } }
+ } } } } } }
+ """.formatted(target));
+ assertNoGraphQLErrors(legacy);
+ final JsonNode legacyItems = legacy.at(
+ "/data/rich/demo_ActionAutoCompletePage/selectTvCharacter/params/tvCharacter/autoComplete");
+ assertThat(legacyItems.size()).isEqualTo(firstWindow.path("totalCount").asInt());
+ assertThat(Stream.concat(
+ firstWindow.at("/items").findValuesAsText("id").stream(),
+ laterWindow.at("/items").findValuesAsText("id").stream()).toList())
+ .containsExactlyElementsOf(legacyItems.findValuesAsText("id"));
+
+ for (String arguments : List.of(
+ "offset: 0, size: 6",
+ "offset: -1, size: 5",
+ "offset: 0, size: 0")) {
+ final JsonNode invalid = graphQL("""
+ { rich { %s { selectTvCharacter { params { tvCharacter {
+ autoCompleteWindow(search: "protected-search", %s) { totalCount }
+ } } } } } }
+ """.formatted(target, arguments));
+ assertThat(invalid.at("/errors/0/message").asText())
+ .containsIgnoringCase("autocomplete window")
+ .doesNotContain("protected-search");
+ }
+ }
+
@Test
void compositeViewModelIdentityRoundTripsThroughTheBoundedCanonicalRoute() throws Exception {
final JsonNode opened = graphQL("""
diff --git a/regressiontests/referenceapp/support-jpa/src/main/java/org/apache/causeway/regressiontests/referenceapp/inventory/ReferenceAppCapabilityInventory.java b/regressiontests/referenceapp/support-jpa/src/main/java/org/apache/causeway/regressiontests/referenceapp/inventory/ReferenceAppCapabilityInventory.java
index 89f98790fec..b7f153fc8b9 100644
--- a/regressiontests/referenceapp/support-jpa/src/main/java/org/apache/causeway/regressiontests/referenceapp/inventory/ReferenceAppCapabilityInventory.java
+++ b/regressiontests/referenceapp/support-jpa/src/main/java/org/apache/causeway/regressiontests/referenceapp/inventory/ReferenceAppCapabilityInventory.java
@@ -174,6 +174,7 @@ private void normalizeConditionalValueHolderMembers(final List<Item> items, fina
}
final Set<String> conditionalIds = Set.of(
+ "rich__demo_ValueHolder__name__gqlv_property",
"rich__demo_ValueHolder__blob__gqlv_property",
"rich__demo_ValueHolder__count__gqlv_property",
"rich__demo_ValueHolder__incrementRedirectEvenIfSame__gqlv_action",
@@ -181,6 +182,12 @@ private void normalizeConditionalValueHolderMembers(final List<Item> items, fina
items.removeIf(item -> conditionalIds.contains(item.id()));
final String reason = "The effective metamodel conditionally advertises this abstract ValueHolder member; "
+ "the reviewed inventory retains it explicitly without claiming deterministic runtime support.";
+ items.add(new Item(
+ "rich__demo_ValueHolder__name__gqlv_property",
+ "PROPERTY",
+ "String",
+ Classification.SUPPORTED,
+ "The value shape has an existing scalar, enum, reference, collection, or resource presentation contract."));
items.add(new Item(
"rich__demo_ValueHolder__blob__gqlv_property",
"PROPERTY",
diff --git a/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json b/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
index 60631a164dc..a6ccaaea1ee 100644
--- a/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
+++ b/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
@@ -4,6 +4,7 @@
"targets": [
{"family": "action-choices", "rootField": "demo_ActionChoices", "member": "selectTvCharacter"},
{"family": "action-autocomplete", "rootField": "demo_ActionAutoCompletePage", "member": "selectTvCharacter"},
+ {"family": "reference-autocomplete-window", "rootField": "demo_ActionAutoCompletePage", "member": "selectTvCharacter"},
{"family": "action-defaults", "rootField": "demo_ActionDefaults", "member": "selectTvCharacterByShow"},
{"family": "action-validation", "rootField": "demo_ActionValidatePage", "member": "selectTvCharactersByShowAndSexUsingName"},
{"family": "action-parameterless", "rootField": "demo_ActionSemanticsVm", "member": "reportPropertyForSafe"},
diff --git a/viewers/graphql/adoc/modules/ROOT/pages/setup-and-configuration.adoc b/viewers/graphql/adoc/modules/ROOT/pages/setup-and-configuration.adoc
index cdadfeeca47..61ef0720362 100644
--- a/viewers/graphql/adoc/modules/ROOT/pages/setup-and-configuration.adoc
+++ b/viewers/graphql/adoc/modules/ROOT/pages/setup-and-configuration.adoc
@@ -107,6 +107,18 @@ It defaults to "`_target`".
+=== Bounded autocomplete response windows
+
+Every rich property or action parameter that advertises `autoComplete(search)` also advertises the additive `autoCompleteWindow(search, offset, size)` field.
+The window returns `items`, offset and requested size, returned and total counts, configured maximum, previous and next availability, and `APPLICATION` ordering.
+One request invokes the authoritative application autocomplete semantic once, preserves that execution's encounter order, and returns only the requested response slice.
+This bounds GraphQL response transfer but does not claim persistence query pushdown, cursor stability, or a cross-request snapshot.
+
+`autocomplete.default-window-size` defaults to `20` and supplies an omitted size.
+`autocomplete.max-window-size` defaults to `100` and rejects larger requests before invoking autocomplete.
+The default must not exceed the maximum.
+Existing `autoComplete(search)` documents remain compatible.
+
The remaining configuration properties are explained in more detail elsewhere:
* xref:refguide:config:sections/causeway.viewer.graphql.adoc#causeway.viewer.graphql.resources.response-type[resources.response-type]
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/TypeNames.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/TypeNames.java
index 914b42e435a..05ca54de53a 100644
--- a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/TypeNames.java
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/TypeNames.java
@@ -112,6 +112,20 @@ public String propertyTypeNameFor(
return objectTypeNameFor(owningType, schemaType) + "__" + otoa.asciiId() + "__gqlv_property";
}
+ public String propertyAutocompleteWindowTypeNameFor(
+ final ObjectSpecification owningType,
+ final OneToOneAssociation otoa,
+ final SchemaType schemaType) {
+ return propertyTypeNameFor(owningType, otoa, schemaType) + "_autocomplete_window";
+ }
+
+ public String actionParamAutocompleteWindowTypeNameFor(
+ final ObjectSpecification owningType,
+ final ObjectActionParameter oap,
+ final SchemaType schemaType) {
+ return actionParamTypeNameFor(owningType, oap, schemaType) + "_autocomplete_window";
+ }
+
public String propertyLobTypeNameFor(
final ObjectSpecification owningType,
final OneToOneAssociation otoa,
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/AutoCompleteWindowOrdering.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/AutoCompleteWindowOrdering.java
new file mode 100644
index 00000000000..af958a9220d
--- /dev/null
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/AutoCompleteWindowOrdering.java
@@ -0,0 +1,23 @@
+/*
+ * 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.
+ */
+package org.apache.causeway.viewer.graphql.model.domain.rich.query;
+
+enum AutoCompleteWindowOrdering {
+ APPLICATION
+}
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichActionParamsParam.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichActionParamsParam.java
index 670ddcdc81b..3fd5650eff0 100644
--- a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichActionParamsParam.java
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichActionParamsParam.java
@@ -63,6 +63,7 @@ public class RichActionParamsParam
* Populated iff there is an autocomplete for this param
*/
private final RichActionParamsParamAutoComplete autoComplete;
+ private final RichActionParamsParamAutoCompleteWindow autoCompleteWindow;
/**
* Populated iff there is a default for this param
*/
@@ -88,6 +89,7 @@ public RichActionParamsParam(
this.disabled = null;
this.choices = null;
this.autoComplete = null;
+ this.autoCompleteWindow = null;
this.default_ = null;
this.validate = null;
this.datatype = null;
@@ -103,6 +105,9 @@ public RichActionParamsParam(
addChildFieldFor(this.disabled = new RichActionParamsParamDisabled(this, context));
addChildFieldFor(this.choices = new RichActionParamsParamChoices(this, context));
addChildFieldFor(this.autoComplete = new RichActionParamsParamAutoComplete(this, context));
+ addChildFieldFor(this.autoCompleteWindow = oap.hasAutoComplete()
+ ? new RichActionParamsParamAutoCompleteWindow(this, context)
+ : null);
addChildFieldFor(this.default_ = new RichActionParamsParamDefault(this, context));
addChildFieldFor(this.validate = new RichActionParamsParamValidate(this, context));
addChildFieldFor(this.datatype = new RichActionParamsParamDatatype(this, context));
@@ -160,6 +165,9 @@ protected void addDataFetchersForChildren() {
if (autoComplete != null) {
autoComplete.addDataFetcher(this);
}
+ if (autoCompleteWindow != null) {
+ autoCompleteWindow.addDataFetcher(this);
+ }
if (default_ != null) {
default_.addDataFetcher(this);
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichActionParamsParamAutoCompleteWindow.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichActionParamsParamAutoCompleteWindow.java
new file mode 100644
index 00000000000..abefd5c8f90
--- /dev/null
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichActionParamsParamAutoCompleteWindow.java
@@ -0,0 +1,83 @@
+/*
+ * 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.
+ */
+package org.apache.causeway.viewer.graphql.model.domain.rich.query;
+
+import java.util.List;
+
+import graphql.schema.DataFetchingEnvironment;
+
+import org.apache.causeway.applib.annotation.Where;
+import org.apache.causeway.core.metamodel.consent.InteractionInitiatedBy;
+import org.apache.causeway.core.metamodel.interactions.managed.ManagedAction;
+import org.apache.causeway.core.metamodel.interactions.managed.ParameterNegotiationModel;
+import org.apache.causeway.core.metamodel.object.ManagedObject;
+import org.apache.causeway.core.metamodel.spec.feature.ObjectFeature;
+import org.apache.causeway.viewer.graphql.model.context.Context;
+import org.apache.causeway.viewer.graphql.model.domain.Environment;
+import org.apache.causeway.viewer.graphql.model.domain.TypeNames;
+import org.apache.causeway.viewer.graphql.model.domain.common.interactors.ActionParamInteractor;
+import org.apache.causeway.viewer.graphql.model.fetcher.BookmarkedPojo;
+import org.apache.causeway.viewer.graphql.model.types.TypeMapper;
+
+final class RichActionParamsParamAutoCompleteWindow extends RichAutoCompleteWindow {
+
+ private final ActionParamInteractor actionParamInteractor;
+
+ RichActionParamsParamAutoCompleteWindow(
+ final ActionParamInteractor actionParamInteractor,
+ final Context context) {
+ super(
+ context,
+ TypeNames.actionParamAutocompleteWindowTypeNameFor(
+ actionParamInteractor.getObjectSpecification(),
+ actionParamInteractor.getObjectActionParameter(),
+ actionParamInteractor.getSchemaType()),
+ context.typeMapper.outputTypeFor(
+ actionParamInteractor.getObjectActionParameter().getElementType(),
+ actionParamInteractor.getSchemaType()),
+ builder -> actionParamInteractor.addGqlArguments(
+ actionParamInteractor.getObjectMember(),
+ builder,
+ TypeMapper.InputContext.AUTOCOMPLETE,
+ actionParamInteractor.getParamNum()));
+ this.actionParamInteractor = actionParamInteractor;
+ }
+
+ @Override
+ protected List<Object> autocompleteItems(final DataFetchingEnvironment environment) {
+ var sourcePojo = BookmarkedPojo.sourceFrom(environment);
+ var objectSpecification = context.specificationLoader.loadSpecification(sourcePojo.getClass());
+ if (objectSpecification == null) {
+ return List.of();
+ }
+
+ var objectAction = actionParamInteractor.getObjectMember();
+ var managedObject = ManagedObject.adaptSingular(objectSpecification, sourcePojo);
+ final ObjectFeature objectFeature = actionParamInteractor.getObjectActionParameter();
+ var objectActionParameter = objectAction.getParameterById(objectFeature.asciiId());
+ var argumentManagedObjects = actionParamInteractor.argumentManagedObjectsFor(
+ new Environment.For(environment), objectAction, context.bookmarkService);
+ var managedAction = ManagedAction.of(managedObject, objectAction, Where.ANYWHERE);
+ var pendingArgs = ParameterNegotiationModel.of(managedAction, argumentManagedObjects);
+ var search = environment.<String>getArgument(SEARCH_ARGUMENT);
+ return objectActionParameter.getAutoComplete(pendingArgs, search, InteractionInitiatedBy.USER).stream()
+ .map(ManagedObject::getPojo)
+ .toList();
+ }
+}
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichAutoCompleteWindow.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichAutoCompleteWindow.java
new file mode 100644
index 00000000000..1073ad3c42b
--- /dev/null
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichAutoCompleteWindow.java
@@ -0,0 +1,167 @@
+/*
+ * 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.
+ */
+package org.apache.causeway.viewer.graphql.model.domain.rich.query;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
+
+import graphql.Scalars;
+import graphql.schema.DataFetchingEnvironment;
+import graphql.schema.GraphQLArgument;
+import graphql.schema.GraphQLEnumType;
+import graphql.schema.GraphQLFieldDefinition;
+import graphql.schema.GraphQLObjectType;
+import graphql.schema.GraphQLOutputType;
+
+import static graphql.schema.GraphQLEnumType.newEnum;
+import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;
+import static graphql.schema.GraphQLList.list;
+import static graphql.schema.GraphQLNonNull.nonNull;
+import static graphql.schema.GraphQLObjectType.newObject;
+
+import org.apache.causeway.viewer.graphql.model.context.Context;
+import org.apache.causeway.viewer.graphql.model.domain.Element;
+import org.apache.causeway.viewer.graphql.model.exceptions.InvalidAutoCompleteWindowException;
+
+abstract class RichAutoCompleteWindow extends Element {
+
+ static final String SEARCH_ARGUMENT = "search";
+ static final String OFFSET_ARGUMENT = "offset";
+ static final String SIZE_ARGUMENT = "size";
+
+ private static final String ORDERING_TYPE_NAME = "rich__gqlv_autocomplete_window_ordering";
+
+ private final int defaultWindowSize;
+ private final int maxWindowSize;
+
+ RichAutoCompleteWindow(
+ final Context context,
+ final String resultTypeName,
+ final GraphQLOutputType itemType,
+ final Consumer<GraphQLFieldDefinition.Builder> dependentArguments) {
+ super(context);
+ this.defaultWindowSize = graphqlConfiguration.autocomplete().defaultWindowSize();
+ this.maxWindowSize = graphqlConfiguration.autocomplete().maxWindowSize();
+
+ var resultType = resultType(context, resultTypeName, itemType, orderingType(context));
+ var fieldBuilder = newFieldDefinition()
+ .name("autoCompleteWindow")
+ .description("Returns a bounded response window over one authoritative autocomplete execution; "
+ + "the configured maximum size is " + maxWindowSize + ".")
+ .type(resultType);
+ dependentArguments.accept(fieldBuilder);
+ fieldBuilder
+ .argument(GraphQLArgument.newArgument()
+ .name(SEARCH_ARGUMENT)
+ .type(nonNull(context.typeMapper.outputTypeFor(String.class))))
+ .argument(GraphQLArgument.newArgument()
+ .name(OFFSET_ARGUMENT)
+ .type(nonNull(Scalars.GraphQLInt))
+ .defaultValueProgrammatic(0))
+ .argument(GraphQLArgument.newArgument()
+ .name(SIZE_ARGUMENT)
+ .type(nonNull(Scalars.GraphQLInt))
+ .defaultValueProgrammatic(defaultWindowSize));
+ setField(fieldBuilder.build());
+ }
+
+ @Override
+ protected final Object fetchData(final DataFetchingEnvironment environment) {
+ var offset = environment.<Integer>getArgument(OFFSET_ARGUMENT);
+ var size = environment.<Integer>getArgument(SIZE_ARGUMENT);
+ validate(offset, size);
+
+ var items = autocompleteItems(environment);
+ var safeItems = items == null ? List.of() : List.copyOf(items);
+ var totalCount = safeItems.size();
+ var fromIndex = Math.min(offset, totalCount);
+ var toIndex = (int) Math.min(totalCount, (long) offset + size);
+ var selectedItems = List.copyOf(safeItems.subList(fromIndex, toIndex));
+
+ Map<String, Object> result = new LinkedHashMap<>();
+ result.put("items", selectedItems);
+ result.put("offset", offset);
+ result.put("requestedSize", size);
+ result.put("returnedCount", selectedItems.size());
+ result.put("totalCount", totalCount);
+ result.put("maximumSize", maxWindowSize);
+ result.put("hasPrevious", offset > 0 && totalCount > 0);
+ result.put("hasNext", (long) offset + selectedItems.size() < totalCount);
+ result.put("ordering", AutoCompleteWindowOrdering.APPLICATION);
+ return Map.copyOf(result);
+ }
+
+ protected abstract List<Object> autocompleteItems(DataFetchingEnvironment environment);
+
+ private void validate(final Integer offset, final Integer size) {
+ if (offset == null || offset < 0) {
+ throw new InvalidAutoCompleteWindowException(
+ "Autocomplete window offset must be zero or greater.");
+ }
+ if (size == null || size < 1) {
+ throw new InvalidAutoCompleteWindowException(
+ "Autocomplete window size must be greater than zero.");
+ }
+ if (size > maxWindowSize) {
+ throw new InvalidAutoCompleteWindowException(
+ "Autocomplete window size exceeds the configured maximum of " + maxWindowSize + ".");
+ }
+ }
+
+ private static GraphQLEnumType orderingType(final Context context) {
+ return context.graphQLTypeRegistry.lookup(ORDERING_TYPE_NAME, GraphQLEnumType.class)
+ .orElseGet(() -> {
+ var type = newEnum()
+ .name(ORDERING_TYPE_NAME)
+ .description("How autocomplete items were ordered before selecting a response window.")
+ .value(AutoCompleteWindowOrdering.APPLICATION.name(), AutoCompleteWindowOrdering.APPLICATION,
+ "The authoritative application autocomplete encounter order for this execution.")
+ .build();
+ context.graphQLTypeRegistry.addTypeIfNotAlreadyPresent(type);
+ return type;
+ });
+ }
+
+ private static GraphQLObjectType resultType(
+ final Context context,
+ final String resultTypeName,
+ final GraphQLOutputType itemType,
+ final GraphQLEnumType orderingType) {
+ return context.graphQLTypeRegistry.lookup(resultTypeName, GraphQLObjectType.class)
+ .orElseGet(() -> {
+ var type = newObject()
+ .name(resultTypeName)
+ .description("A bounded response window over one Causeway autocomplete execution.")
+ .field(newFieldDefinition().name("items").type(list(itemType)))
+ .field(newFieldDefinition().name("offset").type(nonNull(Scalars.GraphQLInt)))
+ .field(newFieldDefinition().name("requestedSize").type(nonNull(Scalars.GraphQLInt)))
+ .field(newFieldDefinition().name("returnedCount").type(nonNull(Scalars.GraphQLInt)))
+ .field(newFieldDefinition().name("totalCount").type(nonNull(Scalars.GraphQLInt)))
+ .field(newFieldDefinition().name("maximumSize").type(nonNull(Scalars.GraphQLInt)))
+ .field(newFieldDefinition().name("hasPrevious").type(nonNull(Scalars.GraphQLBoolean)))
+ .field(newFieldDefinition().name("hasNext").type(nonNull(Scalars.GraphQLBoolean)))
+ .field(newFieldDefinition().name("ordering").type(nonNull(orderingType)))
+ .build();
+ context.graphQLTypeRegistry.addTypeIfNotAlreadyPresent(type);
+ return type;
+ });
+ }
+}
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichProperty.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichProperty.java
index 164eac7e4d0..7adee4d8b58 100644
--- a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichProperty.java
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichProperty.java
@@ -55,6 +55,7 @@ public class RichProperty
* Populated iff there is an autoComplete
*/
private final RichPropertyAutoComplete autoComplete;
+ private final RichPropertyAutoCompleteWindow autoCompleteWindow;
private final RichPropertyValidate validate;
/**
* Populated iff the API variant allows for it.
@@ -74,6 +75,7 @@ public RichProperty(
this.disabled = null;
this.choices = null;
this.autoComplete = null;
+ this.autoCompleteWindow = null;
this.validate = null;
this.set = null;
this.datatype = null;
@@ -94,6 +96,9 @@ public RichProperty(
addChildFieldFor(this.validate = new RichPropertyValidate(this, context));
addChildFieldFor(this.choices = new RichPropertyChoices(this, context));
addChildFieldFor(this.autoComplete = new RichPropertyAutoComplete(this, context));
+ addChildFieldFor(this.autoCompleteWindow = otoa.hasAutoComplete()
+ ? new RichPropertyAutoCompleteWindow(this, context)
+ : null);
addChildFieldFor(this.set = isSetterAllowed() ? new RichPropertySet(this, context) : null);
addChildFieldFor(this.datatype = new RichPropertyDatatype(this, context));
@@ -162,6 +167,9 @@ protected void addDataFetchersForChildren() {
if(autoComplete != null) {
autoComplete.addDataFetcher(this);
}
+ if (autoCompleteWindow != null) {
+ autoCompleteWindow.addDataFetcher(this);
+ }
validate.addDataFetcher(this);
if (set != null) {
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichPropertyAutoCompleteWindow.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichPropertyAutoCompleteWindow.java
new file mode 100644
index 00000000000..de54af29691
--- /dev/null
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichPropertyAutoCompleteWindow.java
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+package org.apache.causeway.viewer.graphql.model.domain.rich.query;
+
+import java.util.List;
+
+import graphql.schema.DataFetchingEnvironment;
+
+import org.apache.causeway.core.metamodel.consent.InteractionInitiatedBy;
+import org.apache.causeway.core.metamodel.object.ManagedObject;
+import org.apache.causeway.core.metamodel.spec.feature.OneToOneAssociation;
+import org.apache.causeway.viewer.graphql.model.context.Context;
+import org.apache.causeway.viewer.graphql.model.domain.SchemaType;
+import org.apache.causeway.viewer.graphql.model.domain.TypeNames;
+import org.apache.causeway.viewer.graphql.model.domain.common.interactors.MemberInteractor;
+import org.apache.causeway.viewer.graphql.model.fetcher.BookmarkedPojo;
+
+final class RichPropertyAutoCompleteWindow extends RichAutoCompleteWindow {
+
+ private final MemberInteractor<OneToOneAssociation> memberInteractor;
+
+ RichPropertyAutoCompleteWindow(
+ final MemberInteractor<OneToOneAssociation> memberInteractor,
+ final Context context) {
+ super(
+ context,
+ TypeNames.propertyAutocompleteWindowTypeNameFor(
+ memberInteractor.getObjectSpecification(),
+ memberInteractor.getObjectMember(),
+ memberInteractor.getSchemaType()),
+ context.typeMapper.outputTypeFor(
+ memberInteractor.getObjectMember().getElementType(), SchemaType.RICH),
+ builder -> { });
+ this.memberInteractor = memberInteractor;
+ }
+
+ @Override
+ protected List<Object> autocompleteItems(final DataFetchingEnvironment environment) {
+ var sourcePojo = BookmarkedPojo.sourceFrom(environment);
+ var objectSpecification = context.specificationLoader.loadSpecification(sourcePojo.getClass());
+ if (objectSpecification == null) {
+ return List.of();
+ }
+
+ var association = memberInteractor.getObjectMember();
+ var managedObject = ManagedObject.adaptSingular(objectSpecification, sourcePojo);
+ var search = environment.<String>getArgument(SEARCH_ARGUMENT);
+ return association.getAutoComplete(managedObject, search, InteractionInitiatedBy.USER).stream()
+ .map(ManagedObject::getPojo)
+ .toList();
+ }
+}
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/exceptions/InvalidAutoCompleteWindowException.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/exceptions/InvalidAutoCompleteWindowException.java
new file mode 100644
index 00000000000..2d3d2f3f190
--- /dev/null
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/exceptions/InvalidAutoCompleteWindowException.java
@@ -0,0 +1,26 @@
+/*
+ * 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.
+ */
+package org.apache.causeway.viewer.graphql.model.exceptions;
+
+public class InvalidAutoCompleteWindowException extends InteractionException {
+
+ public InvalidAutoCompleteWindowException(final String message) {
+ super(message);
+ }
+}
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistry.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistry.java
index 32364dbecf1..f023fdb1887 100644
--- a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistry.java
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistry.java
@@ -57,11 +57,11 @@ public class GraphQLTypeRegistry {
Set<GraphQLType> graphQLTypes = new HashSet<>();
- public Set<GraphQLType> getGraphQLTypes() {
- return Collections.unmodifiableSet(graphQLTypes);
+ public synchronized Set<GraphQLType> getGraphQLTypes() {
+ return Collections.unmodifiableSet(new HashSet<>(graphQLTypes));
}
- void addTypeIfNotAlreadyPresent(
+ synchronized void addTypeIfNotAlreadyPresent(
final GraphQLObjectType typeToAdd,
final String logicalTypeName){
@@ -73,7 +73,7 @@ void addTypeIfNotAlreadyPresent(
graphQLTypes.add(typeToAdd);
}
- public GraphQLEnumType addEnumTypeIfNotAlreadyPresent(
+ public synchronized GraphQLEnumType addEnumTypeIfNotAlreadyPresent(
final Class<?> typeToAdd,
final SchemaType schemaType) {
var objectSpec = contextProvider.get().specificationLoader.loadSpecification(typeToAdd);
@@ -98,7 +98,7 @@ public GraphQLEnumType addEnumTypeIfNotAlreadyPresent(
return enumType;
}
- public void addTypeIfNotAlreadyPresent(final GraphQLType typeToAdd) {
+ public synchronized void addTypeIfNotAlreadyPresent(final GraphQLType typeToAdd) {
if (typeToAdd instanceof GraphQLEnumType) {
addTypeIfNotAlreadyPresent((GraphQLEnumType) typeToAdd);
@@ -131,7 +131,7 @@ public void addTypeIfNotAlreadyPresent(final GraphQLType typeToAdd) {
log.warn("GraphQLType {} not yet implemented", typeToAdd.getClass().getName());
}
- void addTypeIfNotAlreadyPresent(final GraphQLEnumType typeToAdd){
+ synchronized void addTypeIfNotAlreadyPresent(final GraphQLEnumType typeToAdd){
if (isPresent(typeToAdd, GraphQLEnumType.class)){
// For now we just log and skip
log.debug("GraphQLEnumType for {} already present", typeToAdd.getName());
@@ -140,7 +140,7 @@ void addTypeIfNotAlreadyPresent(final GraphQLEnumType typeToAdd){
add(typeToAdd);
}
- void addTypeIfNotAlreadyPresent(final GraphQLObjectType typeToAdd){
+ synchronized void addTypeIfNotAlreadyPresent(final GraphQLObjectType typeToAdd){
if (isPresent(typeToAdd, GraphQLObjectType.class)){
// For now we just log and skip
log.debug("GraphQLObjectType for {} already present", typeToAdd.getName());
@@ -149,7 +149,7 @@ void addTypeIfNotAlreadyPresent(final GraphQLObjectType typeToAdd){
add(typeToAdd);
}
- void addTypeIfNotAlreadyPresent(final GraphQLInputObjectType typeToAdd) {
+ synchronized void addTypeIfNotAlreadyPresent(final GraphQLInputObjectType typeToAdd) {
if (isPresent(typeToAdd, GraphQLInputObjectType.class)){
// For now we just log and skip
log.debug("GraphQLInputObjectType for {} already present", typeToAdd.getName());
@@ -158,7 +158,7 @@ void addTypeIfNotAlreadyPresent(final GraphQLInputObjectType typeToAdd) {
add(typeToAdd);
}
- public GraphQLUnionType addUnionTypeIfNotAlreadyPresent(final GraphQLUnionType typeToAdd) {
+ public synchronized GraphQLUnionType addUnionTypeIfNotAlreadyPresent(final GraphQLUnionType typeToAdd) {
var existing = lookup(typeToAdd.getName(), GraphQLUnionType.class);
if (existing.isPresent()) {
var existingType = existing.get();
@@ -190,7 +190,7 @@ private boolean isPresent(
.anyMatch(ot -> ot.getName().equals(typeToAdd.getName()));
}
- public <T extends GraphQLNamedType> Optional<T> lookup(
+ public synchronized <T extends GraphQLNamedType> Optional<T> lookup(
final String typeName,
final Class<T> cls) {
return graphQLTypes.stream()
diff --git a/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/AutoCompleteWindowConfigurationTest.java b/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/AutoCompleteWindowConfigurationTest.java
new file mode 100644
index 00000000000..83f9cbf2373
--- /dev/null
+++ b/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/AutoCompleteWindowConfigurationTest.java
@@ -0,0 +1,40 @@
+/*
+ * 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.
+ */
+package org.apache.causeway.viewer.graphql.model.domain.rich.query;
+
+import org.junit.jupiter.api.Test;
+
+import org.apache.causeway.core.config.CausewayConfiguration;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class AutoCompleteWindowConfigurationTest {
+
+ @Test
+ void acceptsAValidDefaultAndMaximum() {
+ assertDoesNotThrow(() -> new CausewayConfiguration.Viewer.Graphql.Autocomplete(20, 100));
+ }
+
+ @Test
+ void rejectsADefaultAboveTheMaximum() {
+ assertThrows(IllegalArgumentException.class,
+ () -> new CausewayConfiguration.Viewer.Graphql.Autocomplete(101, 100));
+ }
+}
diff --git a/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistryUnionTest.java b/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistryUnionTest.java
index 25ea4b4e431..08be57dd075 100644
--- a/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistryUnionTest.java
+++ b/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistryUnionTest.java
@@ -20,12 +20,14 @@
import java.util.Set;
import java.util.stream.Collectors;
+import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
import graphql.schema.GraphQLTypeReference;
import graphql.schema.GraphQLUnionType;
+import static graphql.schema.GraphQLObjectType.newObject;
import static graphql.schema.GraphQLUnionType.newUnionType;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
@@ -46,6 +48,16 @@ void repeatedUnionRegistrationMergesPossibleTypesByName() {
assertEquals(1, registry.getGraphQLTypes().size());
}
+ @Test
+ void concurrentRegistrationRetainsEveryDistinctType() {
+ var registry = new GraphQLTypeRegistry(null);
+
+ IntStream.range(0, 1_000).parallel().forEach(index ->
+ registry.addTypeIfNotAlreadyPresent(newObject().name("Type" + index).build()));
+
+ assertEquals(1_000, registry.getGraphQLTypes().size());
+ }
+
private static GraphQLUnionType union(final String name, final String... possibleTypes) {
var builder = newUnionType().name(name);
for (var possibleType : possibleTypes) {
diff --git a/viewers/webcomponents/foundation/USAGE.adoc b/viewers/webcomponents/foundation/USAGE.adoc
index e92ceb2e4a3..d6240ac8f5a 100644
--- a/viewers/webcomponents/foundation/USAGE.adoc
+++ b/viewers/webcomponents/foundation/USAGE.adoc
@@ -318,8 +318,12 @@ await import('/causeway-webcomponents/index.mjs');
----
Eligible fixed choices must contain stable object identities and remain within `maximumResults`.
-Eligible autocomplete inputs use the existing public GraphQL search operation, debounce for 250 milliseconds, cancel superseded work, and reject stale route generations.
-The current GraphQL operation is not server-paged; the maximum is an honest accepted-response bound rather than a page size, and an over-bound result produces a refinement error instead of silent truncation.
+Eligible autocomplete inputs prefer the advertised public `autoCompleteWindow` field, debounce filter changes, request the introspected default page size, cancel superseded work, and reject stale route generations.
+The window is an honest bounded server response slice over one authoritative application autocomplete execution.
+It reports total and continuation metadata but does not claim persistence query pushdown or a cross-request snapshot.
+The internal Vaadin data provider maps its filter, page, and page-size callback to semantic context requests and receives authoritative items and total count without exposing Vaadin APIs to applications.
+When only legacy `autoComplete` exists, `maximumResults` remains an accepted complete-response bound and an over-bound result produces a refinement error instead of silent truncation.
+Native autocomplete renders the bounded first window and states when more matches require refinement.
A list-valued input selects Multi-Select Combo Box only when the introspected input and GraphQL interaction already provide authoritative list pending-value semantics.
Unsupported shapes, disabled configuration, over-bound fixed choices, module failure, and rollback retain or recover the existing editor.
diff --git a/viewers/webcomponents/foundation/src/editor-registry.mjs b/viewers/webcomponents/foundation/src/editor-registry.mjs
index 9f360e0e60d..8ac3536e44f 100644
--- a/viewers/webcomponents/foundation/src/editor-registry.mjs
+++ b/viewers/webcomponents/foundation/src/editor-registry.mjs
@@ -90,7 +90,10 @@ const autoCompleteEditor = Object.freeze({
const current = context.value && typeof context.value === 'object'
? normalizeChoice(context.value).encoded
: context.value ?? '';
- return `<input type="text" ${inputAttributes(context)} value="${escapeHtml(current)}" list="${escapeHtml(listId)}"><datalist id="${escapeHtml(listId)}">${options}</datalist>`;
+ const continuation = context.hasMoreSuggestions === true
+ ? '<span class="causeway-autocomplete-continuation" role="status">More matches are available; refine the search.</span>'
+ : '';
+ return `<input type="text" ${inputAttributes(context)} value="${escapeHtml(current)}" list="${escapeHtml(listId)}"><datalist id="${escapeHtml(listId)}">${options}</datalist>${continuation}`;
},
parse: ({value, suggestions = []}) => {
const match = suggestions.map(normalizeChoice).find(choice => choice.encoded === String(value));
diff --git a/viewers/webcomponents/foundation/src/graphql-client.mjs b/viewers/webcomponents/foundation/src/graphql-client.mjs
index 528c91698e6..5dbf98395e0 100644
--- a/viewers/webcomponents/foundation/src/graphql-client.mjs
+++ b/viewers/webcomponents/foundation/src/graphql-client.mjs
@@ -567,9 +567,9 @@ function referencedInteractionTypeNames(typeDescription, generatedTypeName, sche
const consider = (typeRef, fieldName = '') => {
const typeName = namedType(typeRef);
const kind = innermostType(typeRef)?.kind;
- const choiceValue = ['choices', 'default', 'autoComplete'].includes(fieldName)
+ const choiceValue = ['choices', 'default', 'autoComplete', 'autoCompleteWindow'].includes(fieldName)
&& ['OBJECT', 'INTERFACE', 'UNION'].includes(kind);
- const objectValue = ['get', 'rows'].includes(fieldName)
+ const objectValue = ['get', 'rows', 'items'].includes(fieldName)
&& ['OBJECT', 'INTERFACE', 'UNION'].includes(kind);
const objectMetadata = fieldName === '_meta' && kind === 'OBJECT';
if (typeName && (schemaNames.isReachableSupportType(generatedTypeName, typeName)
diff --git a/viewers/webcomponents/foundation/src/interaction-controller-element.mjs b/viewers/webcomponents/foundation/src/interaction-controller-element.mjs
index fc7b0425af4..a082bb2dd08 100644
--- a/viewers/webcomponents/foundation/src/interaction-controller-element.mjs
+++ b/viewers/webcomponents/foundation/src/interaction-controller-element.mjs
@@ -69,7 +69,16 @@ export class CausewayInteractionControllerElement extends HTMLElement {
return;
}
event.stopPropagation();
- void this.loadParameterAutoComplete(parameterId, event.detail.search);
+ const request = event.detail;
+ if (typeof request.respond === 'function') {
+ void this.loadParameterAutoComplete(parameterId, request.search, {
+ offset: request.offset,
+ size: request.size,
+ publish: false
+ }).then(result => request.respond(result));
+ } else {
+ void this.loadParameterAutoComplete(parameterId, request.search);
+ }
});
this.addEventListener('causeway-reference-escape', event => {
if (this.promptState) {
@@ -240,7 +249,7 @@ export class CausewayInteractionControllerElement extends HTMLElement {
return true;
}
- async loadParameterAutoComplete(parameterId, search) {
+ async loadParameterAutoComplete(parameterId, search, {offset = 0, size = null, publish = true} = {}) {
const parameter = this.promptState?.parameters.find(candidate => candidate.id === parameterId);
if (!parameter?.fields.has('autoComplete') || this.promptState.status === InteractionStatus.INVOKING) {
return {status: InteractionStatus.UNSUPPORTED, data: null, errors: []};
@@ -249,13 +258,24 @@ export class CausewayInteractionControllerElement extends HTMLElement {
const controller = new AbortController();
this.autoCompleteController = controller;
const generation = ++this.autoCompleteGeneration;
- const result = await this.promptState.context.autoCompleteActionParameter(
- this.promptState.actionId,
- parameterId,
- search,
- this.promptState.values,
- {signal: controller.signal}
- );
+ const {maximumResults} = causewayReferenceWidgetConfiguration();
+ const requestedSize = size ?? parameter.autoCompleteWindow?.sizeDefault ?? maximumResults;
+ const context = this.promptState.context;
+ const result = typeof context.autoCompleteActionParameterWindow === 'function'
+ ? await context.autoCompleteActionParameterWindow(
+ this.promptState.actionId,
+ parameterId,
+ search,
+ this.promptState.values,
+ {offset, size: requestedSize, signal: controller.signal}
+ )
+ : legacyWindowResult(await context.autoCompleteActionParameter(
+ this.promptState.actionId,
+ parameterId,
+ search,
+ this.promptState.values,
+ {signal: controller.signal}
+ ), offset, requestedSize);
if (generation !== this.autoCompleteGeneration || controller.signal.aborted || !this.promptState) {
return {...result, status: InteractionStatus.OBSOLETE};
}
@@ -267,22 +287,28 @@ export class CausewayInteractionControllerElement extends HTMLElement {
}
return result;
}
- const suggestions = [...(result.data ?? [])];
- const {maximumResults} = causewayReferenceWidgetConfiguration();
- if (suggestions.length > maximumResults) {
+ const window = result.data;
+ const suggestions = [...(window?.items ?? [])];
+ if (window?.windowed !== true && suggestions.length > maximumResults) {
const message = `More than ${maximumResults} references matched. Refine the search.`;
this.promptState = Object.freeze({...this.promptState, status: InteractionStatus.FAILED, error: message});
this.#publishPromptState();
this.render();
return {status: InteractionStatus.FAILED, data: null, errors: [{message, code: 'AUTOCOMPLETE_RESULT_LIMIT'}]};
}
- const parameters = Object.freeze(this.promptState.parameters.map(candidate => candidate.id === parameterId
- ? Object.freeze({...candidate, state: Object.freeze({...candidate.state, suggestions: Object.freeze(suggestions)})})
- : candidate));
- this.promptState = Object.freeze({...this.promptState, status: InteractionStatus.EDITING, parameters, error: null});
- this.#publishPromptState();
- this.render();
- this.#focusFirstControl();
+ if (publish) {
+ const parameters = Object.freeze(this.promptState.parameters.map(candidate => candidate.id === parameterId
+ ? Object.freeze({...candidate, state: Object.freeze({
+ ...candidate.state,
+ suggestions: Object.freeze(suggestions),
+ autoCompleteWindow: window
+ })})
+ : candidate));
+ this.promptState = Object.freeze({...this.promptState, status: InteractionStatus.EDITING, parameters, error: null});
+ this.#publishPromptState();
+ this.render();
+ this.#focusFirstControl();
+ }
return result;
}
@@ -423,6 +449,12 @@ export class CausewayInteractionControllerElement extends HTMLElement {
}
const choices = parameter.state?.choices ?? parameter.enumValues ?? [];
const rendered = renderCausewayEditor(this.#parameterEditorContext(parameter, choices), this._editorRegistry);
+ if (rendered.editor.id === 'autocomplete' && event.type === 'input') {
+ clearTimeout(this.parameterTimer);
+ const search = String(event.target.value ?? '');
+ this.parameterTimer = setTimeout(() => void this.loadParameterAutoComplete(parameterId, search), 250);
+ return;
+ }
try {
const value = parseCausewayEditorValue(rendered.editor, {
value: event.target.value,
@@ -524,6 +556,9 @@ export class CausewayInteractionControllerElement extends HTMLElement {
choices,
suggestions: parameter.state?.suggestions ?? [],
autoComplete: parameter.fields.has('autoComplete'),
+ autoCompleteWindow: Boolean(parameter.autoCompleteWindow),
+ autoCompletePageSize: parameter.autoCompleteWindow?.sizeDefault ?? null,
+ hasMoreSuggestions: parameter.state?.autoCompleteWindow?.hasNext === true,
enumValues: parameter.enumValues,
inputType: parameter.inputType,
semanticType: parameter.state?.datatype ?? null,
@@ -630,6 +665,25 @@ export class CausewayInteractionControllerElement extends HTMLElement {
}
}
+function legacyWindowResult(result, offset, requestedSize) {
+ if (result?.status !== InteractionStatus.SUCCESS || !Array.isArray(result.data)) return result;
+ return {
+ ...result,
+ data: Object.freeze({
+ items: Object.freeze([...result.data]),
+ offset,
+ requestedSize,
+ returnedCount: result.data.length,
+ totalCount: result.data.length,
+ maximumSize: null,
+ hasPrevious: false,
+ hasNext: false,
+ ordering: 'LEGACY',
+ windowed: false
+ })
+ };
+}
+
function focusRestoreTarget(source) {
const panel = source?.closest?.('[data-causeway-menu-panel]');
const panelId = panel?.id;
diff --git a/viewers/webcomponents/foundation/src/interaction-operations.mjs b/viewers/webcomponents/foundation/src/interaction-operations.mjs
index 3d1f63d8e1b..fe60f591d4d 100644
--- a/viewers/webcomponents/foundation/src/interaction-operations.mjs
+++ b/viewers/webcomponents/foundation/src/interaction-operations.mjs
@@ -23,6 +23,58 @@ import {INLINE_FRAGMENTS} from './selection.mjs';
export const MAX_DIRECT_FRAGMENT_TYPES = 8;
+const AUTO_COMPLETE_WINDOW_FIELDS = Object.freeze([
+ 'offset',
+ 'requestedSize',
+ 'returnedCount',
+ 'totalCount',
+ 'maximumSize',
+ 'hasPrevious',
+ 'hasNext',
+ 'ordering'
+]);
+
+export function autoCompleteWindowPlan(field, types) {
+ const typeName = namedType(field?.type);
+ const typeDescription = types.get(typeName) ?? null;
+ const fields = fieldsByName(typeDescription);
+ const itemsField = fields.get('items');
+ if (!field || !typeDescription || !itemsField) {
+ return null;
+ }
+ const args = fieldsByName({fields: field.args ?? []});
+ const selection = Object.fromEntries(AUTO_COMPLETE_WINDOW_FIELDS
+ .filter(name => fields.has(name))
+ .map(name => [name, true]));
+ selection.items = resultSelectionForType(itemsField.type, types) ?? true;
+ return Object.freeze({
+ typeName,
+ typeDescription,
+ itemsField,
+ selection: Object.freeze(selection),
+ offsetDefault: integerDefault(args.get('offset')?.defaultValue, 0),
+ sizeDefault: integerDefault(args.get('size')?.defaultValue, null)
+ });
+}
+
+export function normalizeAutoCompleteWindow(value, {legacy = false, offset = 0, requestedSize = null} = {}) {
+ const items = Array.isArray(legacy ? value : value?.items) ? [...(legacy ? value : value.items)] : [];
+ const totalCount = legacy ? items.length : nonNegativeInteger(value?.totalCount, items.length);
+ const effectiveOffset = legacy ? offset : nonNegativeInteger(value?.offset, offset);
+ return Object.freeze({
+ items: Object.freeze(items),
+ offset: effectiveOffset,
+ requestedSize: legacy ? requestedSize : positiveInteger(value?.requestedSize, requestedSize ?? items.length),
+ returnedCount: legacy ? items.length : nonNegativeInteger(value?.returnedCount, items.length),
+ totalCount,
+ maximumSize: legacy ? null : positiveInteger(value?.maximumSize, null),
+ hasPrevious: legacy ? effectiveOffset > 0 : value?.hasPrevious === true,
+ hasNext: legacy ? false : value?.hasNext === true,
+ ordering: legacy ? 'LEGACY' : String(value?.ordering ?? 'APPLICATION'),
+ windowed: !legacy
+ });
+}
+
export function buildDescribeOperationRootsOperation() {
return Object.freeze({
document: 'query CausewayDescribeOperationRoots { __schema { queryType { name } mutationType { name } } }',
@@ -240,6 +292,22 @@ export function resultSelectionForType(typeRef, types) {
: {__typename: true};
}
+function integerDefault(value, fallback) {
+ if (value == null) return fallback;
+ const parsed = Number(value);
+ return Number.isSafeInteger(parsed) ? parsed : fallback;
+}
+
+function nonNegativeInteger(value, fallback) {
+ const parsed = Number(value);
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : fallback;
+}
+
+function positiveInteger(value, fallback) {
+ const parsed = Number(value);
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : fallback;
+}
+
function renderExecutableSelection({
selection,
typeDescription,
diff --git a/viewers/webcomponents/foundation/src/object-context-controller.mjs b/viewers/webcomponents/foundation/src/object-context-controller.mjs
index de520fec19d..2c53f422544 100644
--- a/viewers/webcomponents/foundation/src/object-context-controller.mjs
+++ b/viewers/webcomponents/foundation/src/object-context-controller.mjs
@@ -29,9 +29,11 @@ import {createSemanticEvent, OBJECT_CONTEXT_STATE_EVENT} from './context-events.
import {fieldsByName, namedType} from './introspection.mjs';
import {
argumentsFromValues,
+ autoCompleteWindowPlan,
commandSelection,
MAX_DIRECT_FRAGMENT_TYPES,
metadataSelectionForType,
+ normalizeAutoCompleteWindow,
resultSelectionForType
} from './interaction-operations.mjs';
import {
@@ -159,12 +161,16 @@ export class ObjectContextController extends EventTarget {
const mutationFieldName = mutationFieldNameFor(description, member);
const mutationField = mutationType ? fieldsByName(mutationType).get(mutationFieldName) ?? null : null;
const enumValues = descriptor.value?.typeDescription?.enumValues?.map(value => value.name) ?? [];
+ const autoCompleteWindow = autoCompleteWindowPlan(
+ descriptor.fields.get('autoCompleteWindow'), description.types);
return Object.freeze({
descriptor,
editable: descriptor.fields.has('set') || Boolean(mutationField),
validate: descriptor.fields.has('validate'),
choices: descriptor.fields.has('choices'),
autoComplete: descriptor.fields.has('autoComplete'),
+ autoCompleteWindow: Boolean(autoCompleteWindow),
+ autoCompleteWindowSize: autoCompleteWindow?.sizeDefault ?? null,
mutationFieldName: mutationField ? mutationFieldName : null,
inputType: propertyInputType(descriptor, mutationField, member),
enumValues: Object.freeze(enumValues)
@@ -230,6 +236,38 @@ export class ObjectContextController extends EventTarget {
});
}
+ async autoCompletePropertyWindow(member, search, {offset = 0, size = null, signal} = {}) {
+ const {description, descriptor} = await this.#memberDescriptor(member, 'property');
+ const field = descriptor.fields.get('autoCompleteWindow');
+ if (!field) {
+ const legacy = await this.autoCompleteProperty(member, search, {signal});
+ return legacy.status === InteractionStatus.SUCCESS
+ ? interactionResult(legacy.status, normalizeAutoCompleteWindow(legacy.data, {
+ legacy: true, offset, requestedSize: size
+ }), legacy.errors, legacy.operation)
+ : legacy;
+ }
+ return this.#runTransient(`property:${member}:autocomplete`, signal, async commandSignal => {
+ const plan = autoCompleteWindowPlan(field, description.types);
+ if (!plan) {
+ return interactionResult(InteractionStatus.UNSUPPORTED, null, [commandError(
+ `Property '${member}' exposes an incomplete autocomplete window.`)]);
+ }
+ const args = windowArguments(field, search, offset, size);
+ const result = await this.client.executeObjectInteraction({
+ description,
+ identity: this.identity,
+ selection: {[member]: {autoCompleteWindow: commandSelection(args, plan.selection)}},
+ operationName: 'CausewayPropertyAutoCompleteWindow',
+ signal: commandSignal
+ });
+ return commandResponse(result, normalizeAutoCompleteWindow(
+ result.data?.[member]?.autoCompleteWindow ?? null,
+ {offset, requestedSize: size ?? plan.sizeDefault}
+ ));
+ });
+ }
+
async validateProperty(member, value, {signal} = {}) {
return this.#runTransient(`property:${member}:validate`, signal, async commandSignal => {
const {description, descriptor} = await this.#memberDescriptor(member, 'property');
@@ -302,11 +340,13 @@ export class ObjectContextController extends EventTarget {
const actionArgument = validateField?.args.find(argument => argument.name === field.name) ?? null;
const inputType = actionArgument?.type ?? parameterInputType(wrapper);
const enumType = inputType ? description.types.get(namedType(inputType)) ?? null : null;
+ const fields = fieldsByName(wrapper);
return Object.freeze({
id: field.name,
description: field.description ?? null,
generatedTypeName: wrapper?.name ?? namedType(field.type),
- fields: fieldsByName(wrapper),
+ fields,
+ autoCompleteWindow: autoCompleteWindowPlan(fields.get('autoCompleteWindow'), description.types),
inputType,
enumValues: Object.freeze(enumType?.enumValues?.map(value => value.name) ?? [])
});
@@ -434,6 +474,48 @@ export class ObjectContextController extends EventTarget {
});
}
+ async autoCompleteActionParameterWindow(
+ member,
+ parameterId,
+ search,
+ values = {},
+ {offset = 0, size = null, signal} = {}
+ ) {
+ const {description} = await this.#memberDescriptor(member, 'action');
+ const capabilities = await this.describeActionInteraction(member);
+ const parameter = capabilities.parameters.find(candidate => candidate.id === parameterId);
+ const field = parameter?.fields.get('autoCompleteWindow');
+ if (!field) {
+ const legacy = await this.autoCompleteActionParameter(member, parameterId, search, values, {signal});
+ return legacy.status === InteractionStatus.SUCCESS
+ ? interactionResult(legacy.status, normalizeAutoCompleteWindow(legacy.data, {
+ legacy: true, offset, requestedSize: size
+ }), legacy.errors, legacy.operation)
+ : legacy;
+ }
+ return this.#runTransient(`action:${member}:${parameterId}:autocomplete`, signal, async commandSignal => {
+ const plan = autoCompleteWindowPlan(field, description.types);
+ if (!plan) {
+ return interactionResult(InteractionStatus.UNSUPPORTED, null, [commandError(
+ `Action parameter '${member}.${parameterId}' exposes an incomplete autocomplete window.`)]);
+ }
+ const args = {...argumentsFromValues(field, values), ...windowArguments(field, search, offset, size)};
+ const result = await this.client.executeObjectInteraction({
+ description,
+ identity: this.identity,
+ selection: {
+ [member]: {params: {[parameterId]: {autoCompleteWindow: commandSelection(args, plan.selection)}}}
+ },
+ operationName: 'CausewayActionParameterAutoCompleteWindow',
+ signal: commandSignal
+ });
+ return commandResponse(result, normalizeAutoCompleteWindow(
+ result.data?.[member]?.params?.[parameterId]?.autoCompleteWindow ?? null,
+ {offset, requestedSize: size ?? plan.sizeDefault}
+ ));
+ });
+ }
+
async validateAction(member, values = {}, {signal} = {}) {
return this.#runTransient(`action:${member}:validate`, signal, async commandSignal => {
const {description, descriptor} = await this.#memberDescriptor(member, 'action');
@@ -1009,6 +1091,12 @@ async function ensureResultTypes(client, description, typeRef, signal) {
}
}
+function windowArguments(field, search, offset, size) {
+ const values = {search, offset};
+ if (size != null) values.size = size;
+ return argumentsFromValues(field, values);
+}
+
function mutationFieldNameFor(description, member) {
return `${description.generatedFieldName}__${member}`;
}
diff --git a/viewers/webcomponents/foundation/src/property-element.mjs b/viewers/webcomponents/foundation/src/property-element.mjs
index 9d11b47f9a5..0b86fce3b42 100644
--- a/viewers/webcomponents/foundation/src/property-element.mjs
+++ b/viewers/webcomponents/foundation/src/property-element.mjs
@@ -72,7 +72,16 @@ export class CausewayPropertyElement extends CausewayContextConsumerElement {
return;
}
event.stopPropagation();
- void this.loadAutoComplete(event.detail.search);
+ const request = event.detail;
+ if (typeof request.respond === 'function') {
+ void this.loadAutoComplete(request.search, {
+ offset: request.offset,
+ size: request.size,
+ publish: false
+ }).then(result => request.respond(result));
+ } else {
+ void this.loadAutoComplete(request.search);
+ }
});
this.addEventListener('causeway-reference-escape', event => {
if (this.interactionState) {
@@ -269,7 +278,7 @@ export class CausewayPropertyElement extends CausewayContextConsumerElement {
return true;
}
- async loadAutoComplete(search) {
+ async loadAutoComplete(search, {offset = 0, size = null, publish = true} = {}) {
if (!this.interactionState?.capabilities?.autoComplete) {
return {status: InteractionStatus.UNSUPPORTED, data: null, errors: []};
}
@@ -277,7 +286,18 @@ export class CausewayPropertyElement extends CausewayContextConsumerElement {
const controller = new AbortController();
this.autoCompleteController = controller;
const generation = ++this.autoCompleteGeneration;
- const result = await this._resolvedContext.autoCompleteProperty(this.member, search, {signal: controller.signal});
+ const {maximumResults} = causewayReferenceWidgetConfiguration();
+ const requestedSize = size
+ ?? this.interactionState.capabilities?.autoCompleteWindowSize
+ ?? maximumResults;
+ const result = typeof this._resolvedContext.autoCompletePropertyWindow === 'function'
+ ? await this._resolvedContext.autoCompletePropertyWindow(this.member, search, {
+ offset,
+ size: requestedSize,
+ signal: controller.signal
+ })
+ : legacyWindowResult(await this._resolvedContext.autoCompleteProperty(
+ this.member, search, {signal: controller.signal}), offset, requestedSize);
if (generation !== this.autoCompleteGeneration || controller.signal.aborted || !this.interactionState) {
return {...result, status: InteractionStatus.OBSOLETE};
}
@@ -291,20 +311,23 @@ export class CausewayPropertyElement extends CausewayContextConsumerElement {
}
return result;
}
- const suggestions = [...(result.data ?? [])];
- const {maximumResults} = causewayReferenceWidgetConfiguration();
- if (suggestions.length > maximumResults) {
+ const window = result.data;
+ const suggestions = [...(window?.items ?? [])];
+ if (window?.windowed !== true && suggestions.length > maximumResults) {
const message = `More than ${maximumResults} references matched. Refine the search.`;
this.#setInteraction({...this.interactionState, status: InteractionStatus.FAILED, suggestions: Object.freeze([]), error: message});
return {status: InteractionStatus.FAILED, data: null, errors: [{message, code: 'AUTOCOMPLETE_RESULT_LIMIT'}]};
}
- this.interactionState = Object.freeze({
- ...this.interactionState,
- status: InteractionStatus.EDITING,
- suggestions: Object.freeze(suggestions),
- error: null
- });
- this.renderComponentState(this.componentState);
+ if (publish) {
+ this.interactionState = Object.freeze({
+ ...this.interactionState,
+ status: InteractionStatus.EDITING,
+ suggestions: Object.freeze(suggestions),
+ autoCompleteWindow: window,
+ error: null
+ });
+ this.renderComponentState(this.componentState);
+ }
return result;
}
@@ -429,6 +452,12 @@ export class CausewayPropertyElement extends CausewayContextConsumerElement {
return;
}
const editor = this.interactionState.editor;
+ if (editor.id === 'autocomplete' && debounce) {
+ clearTimeout(this.validationTimer);
+ const search = String(event.target.value ?? '');
+ this.validationTimer = setTimeout(() => void this.loadAutoComplete(search), 250);
+ return;
+ }
try {
const value = parseCausewayEditorValue(editor, {
value: event.target.value,
@@ -502,6 +531,9 @@ export class CausewayPropertyElement extends CausewayContextConsumerElement {
choices: interaction.choices ?? [],
suggestions: interaction.suggestions ?? [],
autoComplete: interaction.capabilities?.autoComplete === true,
+ autoCompleteWindow: interaction.capabilities?.autoCompleteWindow === true,
+ autoCompletePageSize: interaction.capabilities?.autoCompleteWindowSize ?? null,
+ hasMoreSuggestions: interaction.autoCompleteWindow?.hasNext === true,
enumValues: interaction.capabilities?.enumValues ?? [],
inputType: interaction.capabilities?.inputType,
semanticType: this.componentState?.data?.datatype ?? interaction.capabilities?.semanticType ?? null,
@@ -585,6 +617,25 @@ export class CausewayPropertyElement extends CausewayContextConsumerElement {
}
}
+function legacyWindowResult(result, offset, requestedSize) {
+ if (result?.status !== InteractionStatus.SUCCESS || !Array.isArray(result.data)) return result;
+ return {
+ ...result,
+ data: Object.freeze({
+ items: Object.freeze([...result.data]),
+ offset,
+ requestedSize,
+ returnedCount: result.data.length,
+ totalCount: result.data.length,
+ maximumSize: null,
+ hasPrevious: false,
+ hasNext: false,
+ ordering: 'LEGACY',
+ windowed: false
+ })
+ };
+}
+
function publicInteractionValue(editor, value) {
return editor?.codec?.sensitive === true ? null : value;
}
diff --git a/viewers/webcomponents/foundation/src/reference-widget.mjs b/viewers/webcomponents/foundation/src/reference-widget.mjs
index 3f403bdb28b..433aa8f38e7 100644
--- a/viewers/webcomponents/foundation/src/reference-widget.mjs
+++ b/viewers/webcomponents/foundation/src/reference-widget.mjs
@@ -70,6 +70,11 @@ export function renderCausewayReferenceWidget(context) {
if (context.disabled) attributes.push('disabled');
if (context.required) attributes.push('required');
if (context.autoComplete === true) attributes.push('data-autocomplete="true"');
+ if (context.autoCompleteWindow === true) {
+ attributes.push('data-autocomplete-window="true"');
+ attributes.push(`data-autocomplete-page-size="${positiveInteger(context.autoCompletePageSize, configuration.maximumResults)}"`);
+ }
+ if (context.hasMoreSuggestions === true) attributes.push('data-has-more-suggestions="true"');
if (multiple) attributes.push('multiple');
return `<causeway-reference-editor ${attributes.join(' ')}><span role="status">Loading reference editor…</span></causeway-reference-editor>`;
}
@@ -82,6 +87,8 @@ export class CausewayReferenceEditorElement extends HTMLElement {
this._searchTimer = null;
this._syncing = false;
this._value = null;
+ this._filterGeneration = 0;
+ this._activeFilter = null;
this.addEventListener('keydown', event => {
if (event.key === 'Escape' && this._control?.opened !== true) {
this.dispatchEvent(new CustomEvent('causeway-reference-escape', {bubbles: true, composed: true}));
@@ -130,7 +137,14 @@ export class CausewayReferenceEditorElement extends HTMLElement {
control.label = this.dataset.label || this.getAttribute('data-causeway-editor') || 'Reference';
control.itemLabelPath = 'title';
control.itemValuePath = 'id';
- control.items = this.#items();
+ control.itemIdPath = 'id';
+ if (this.dataset.autocompleteWindow === 'true') {
+ control.pageSize = positiveInteger(
+ Number(this.dataset.autocompletePageSize), configuration.maximumResults);
+ control.dataProvider = (params, callback) => this.#providePage(params, callback, generation);
+ } else {
+ control.items = this.#items();
+ }
if (this.hasAttribute('multiple')) control.autoExpandVertically = true;
control.clearButtonVisible = !this.hasAttribute('required');
control.required = this.hasAttribute('required');
@@ -138,7 +152,9 @@ export class CausewayReferenceEditorElement extends HTMLElement {
const describedBy = this.dataset.describedby;
if (describedBy) control.setAttribute('aria-describedby', describedBy);
if (this.dataset.invalid === 'true') control.setAttribute('invalid', '');
- control.addEventListener('filter-changed', event => this.#filterChanged(event));
+ if (this.dataset.autocompleteWindow !== 'true') {
+ control.addEventListener('filter-changed', event => this.#filterChanged(event));
+ }
const selectionEvent = this.hasAttribute('multiple') ? 'selected-items-changed' : 'selected-item-changed';
control.addEventListener(selectionEvent, event => this.#selectionChanged(event));
this.replaceChildren(control);
@@ -206,6 +222,48 @@ export class CausewayReferenceEditorElement extends HTMLElement {
}, 250);
}
+ #providePage(params, callback, connectionGeneration) {
+ const filter = String(params?.filter ?? '').trim();
+ if (filter.length < configuration.minimumSearchLength) {
+ callback([], 0);
+ return;
+ }
+ if (filter !== this._activeFilter) {
+ this._activeFilter = filter;
+ this._filterGeneration += 1;
+ }
+ const filterGeneration = this._filterGeneration;
+ const pageSize = positiveInteger(params?.pageSize, configuration.maximumResults);
+ const page = nonNegativeInteger(params?.page, 0);
+ let responded = false;
+ const respond = result => {
+ if (responded || !this.isConnected || connectionGeneration !== this._generation
+ || filterGeneration !== this._filterGeneration || filter !== this._activeFilter) {
+ return;
+ }
+ responded = true;
+ const window = result?.status === 'success' ? result.data : null;
+ if (!window) {
+ this.dataset.widgetError = result?.errors?.[0]?.message ?? 'Reference page request failed.';
+ } else {
+ delete this.dataset.widgetError;
+ }
+ const items = (window?.items ?? []).map(normalizeReference).filter(Boolean);
+ callback(items, Number(window?.totalCount ?? 0));
+ };
+ this.dispatchEvent(new CustomEvent('causeway-reference-search', {
+ bubbles: true,
+ composed: true,
+ detail: Object.freeze({
+ name: this.getAttribute('data-causeway-editor'),
+ search: filter,
+ offset: page * pageSize,
+ size: pageSize,
+ respond
+ })
+ }));
+ }
+
#selectionChanged(event) {
if (this._syncing) return;
const selected = event.detail?.value;
diff --git a/viewers/webcomponents/foundation/src/service-action-context.mjs b/viewers/webcomponents/foundation/src/service-action-context.mjs
index f6c3fa929f0..24cb32a613f 100644
--- a/viewers/webcomponents/foundation/src/service-action-context.mjs
+++ b/viewers/webcomponents/foundation/src/service-action-context.mjs
@@ -26,7 +26,13 @@ import {
secureActionInvocationResult
} from './action-dispatch.mjs';
import {fieldsByName, namedType} from './introspection.mjs';
-import {argumentsFromValues, commandSelection, resultSelectionForType} from './interaction-operations.mjs';
+import {
+ argumentsFromValues,
+ autoCompleteWindowPlan,
+ commandSelection,
+ normalizeAutoCompleteWindow,
+ resultSelectionForType
+} from './interaction-operations.mjs';
import {InteractionResultKind, InteractionStatus} from './types.mjs';
export class ServiceActionContextController {
@@ -206,6 +212,50 @@ export class ServiceActionContextController {
});
}
+ async autoCompleteActionParameterWindow(
+ actionId,
+ parameterId,
+ search,
+ values = {},
+ {offset = 0, size = null, signal} = {}
+ ) {
+ const description = await this.describeService();
+ const capabilities = await this.describeActionInteraction(actionId);
+ const parameter = capabilities.parameters.find(candidate => candidate.id === parameterId);
+ const field = parameter?.fields.get('autoCompleteWindow');
+ if (!field) {
+ const legacy = await this.autoCompleteActionParameter(actionId, parameterId, search, values, {signal});
+ return legacy.status === InteractionStatus.SUCCESS
+ ? interactionResult(legacy.status, normalizeAutoCompleteWindow(legacy.data, {
+ legacy: true, offset, requestedSize: size
+ }), legacy.errors, legacy.operation)
+ : legacy;
+ }
+ return this.#runTransient(`action:${actionId}:${parameterId}:autocomplete`, signal, async commandSignal => {
+ const plan = autoCompleteWindowPlan(field, description.types);
+ if (!plan) {
+ return interactionResult(InteractionStatus.UNSUPPORTED, null, [commandError(
+ `Service-action parameter '${actionId}.${parameterId}' exposes an incomplete autocomplete window.`)]);
+ }
+ const args = {
+ ...argumentsFromValues(field, values),
+ ...windowArguments(field, search, offset, size)
+ };
+ const result = await this.client.executeServiceInteraction({
+ description,
+ selection: {
+ [actionId]: {params: {[parameterId]: {autoCompleteWindow: commandSelection(args, plan.selection)}}}
+ },
+ operationName: 'CausewayServiceActionParameterAutoCompleteWindow',
+ signal: commandSignal
+ });
+ return commandResponse(result, normalizeAutoCompleteWindow(
+ result.data?.[actionId]?.params?.[parameterId]?.autoCompleteWindow ?? null,
+ {offset, requestedSize: size ?? plan.sizeDefault}
+ ));
+ });
+ }
+
async validateAction(actionId, values = {}, {signal} = {}) {
return this.#runTransient(`action:${actionId}:validate`, signal, async commandSignal => {
const description = await this.describeService();
@@ -306,11 +356,13 @@ export class ServiceActionContextController {
const actionArgument = validateField?.args.find(argument => argument.name === field.name) ?? null;
const inputType = actionArgument?.type ?? parameterInputType(wrapper);
const enumType = inputType ? description.types.get(namedType(inputType)) ?? null : null;
+ const fields = fieldsByName(wrapper);
return Object.freeze({
id: field.name,
description: field.description ?? null,
generatedTypeName: wrapper?.name ?? namedType(field.type),
- fields: fieldsByName(wrapper),
+ fields,
+ autoCompleteWindow: autoCompleteWindowPlan(fields.get('autoCompleteWindow'), description.types),
inputType,
enumValues: Object.freeze(enumType?.enumValues?.map(value => value.name) ?? [])
});
@@ -399,6 +451,12 @@ async function ensureResultTypes(client, description, typeRef, signal) {
}
}
+function windowArguments(field, search, offset, size) {
+ const values = {search, offset};
+ if (size != null) values.size = size;
+ return argumentsFromValues(field, values);
+}
+
function parameterInputType(wrapper) {
if (!wrapper) {
return null;
diff --git a/viewers/webcomponents/foundation/test/application-menu-client.test.mjs b/viewers/webcomponents/foundation/test/application-menu-client.test.mjs
index 83d5dc896c5..bfe5c73c49f 100644
--- a/viewers/webcomponents/foundation/test/application-menu-client.test.mjs
+++ b/viewers/webcomponents/foundation/test/application-menu-client.test.mjs
@@ -127,6 +127,23 @@ test('service action adapter reuses parameter preparation, validation, safe invo
assert.deepEqual(context.interactionTarget, {kind: 'service', logicalTypeName: SAMPLE_SERVICE_LOGICAL_TYPE});
});
+test('service action context executes advertised autocomplete windows', async () => {
+ const executor = createMenuGraphQLExecutor();
+ const client = new CausewayGraphQLClient({executor});
+ const context = new ServiceActionContextController({client, logicalTypeName: SAMPLE_SERVICE_LOGICAL_TYPE});
+
+ const result = await context.autoCompleteActionParameterWindow(
+ 'greet', 'name', 'Gr', {}, {offset: 2, size: 2});
+
+ assert.equal(result.status, InteractionStatus.SUCCESS);
+ assert.deepEqual(result.data.items, ['Grace']);
+ assert.equal(result.data.totalCount, 3);
+ const call = executor.serviceCalls.find(candidate =>
+ candidate.operationName === 'CausewayServiceActionParameterAutoCompleteWindow');
+ assert.deepEqual(Object.values(call.variables), ['Gr', 2, 2]);
+ assert.match(call.document, /autoCompleteWindow/);
+});
+
test('superseded service parameter preparation cannot replace the latest response', async () => {
const base = createMenuGraphQLExecutor();
let releaseFirst;
diff --git a/viewers/webcomponents/foundation/test/fixtures/menu-graphql-fixture.mjs b/viewers/webcomponents/foundation/test/fixtures/menu-graphql-fixture.mjs
index 3c0b63f4a59..de94c71062e 100644
--- a/viewers/webcomponents/foundation/test/fixtures/menu-graphql-fixture.mjs
+++ b/viewers/webcomponents/foundation/test/fixtures/menu-graphql-fixture.mjs
@@ -22,6 +22,8 @@ import {CAUSEWAY_MENU_BARS_NAMESPACE} from '../../src/menu-layout.mjs';
export const SAMPLE_SERVICE_LOGICAL_TYPE = 'causeway.webcomponents.sample.SampleMenu';
export const SAMPLE_SERVICE_FIELD = 'causeway_webcomponents_sample_SampleMenu';
export const SAMPLE_SERVICE_TYPE = 'rich__causeway_webcomponents_sample_SampleMenu';
+const GREET_PARAMETER_TYPE = `${SAMPLE_SERVICE_TYPE}__greet__name__gqlv_action_parameter`;
+const GREET_AUTOCOMPLETE_WINDOW_TYPE = `${GREET_PARAMETER_TYPE}_autocomplete_window`;
export function createMenuGraphQLTypes({menuBarsAvailable = true} = {}) {
const applicationFields = [
@@ -92,14 +94,27 @@ export function createMenuGraphQLTypes({menuBarsAvailable = true} = {}) {
[`${SAMPLE_SERVICE_TYPE}__greet__gqlv_action_params`, objectType(`${SAMPLE_SERVICE_TYPE}__greet__gqlv_action_params`, [
field('name', named(`${SAMPLE_SERVICE_TYPE}__greet__name__gqlv_action_parameter`))
])],
- [`${SAMPLE_SERVICE_TYPE}__greet__name__gqlv_action_parameter`, objectType(`${SAMPLE_SERVICE_TYPE}__greet__name__gqlv_action_parameter`, [
+ [GREET_PARAMETER_TYPE, objectType(GREET_PARAMETER_TYPE, [
field('hidden', scalar('Boolean'), [argument('name', scalar('String'))]),
field('disabled', scalar('String'), [argument('name', scalar('String'))]),
field('default', scalar('String'), [argument('name', scalar('String'))]),
field('choices', list(scalar('String')), [argument('name', scalar('String'))]),
+ field('autoComplete', list(scalar('String')), [argument('search', scalar('String'))]),
+ field('autoCompleteWindow', named(GREET_AUTOCOMPLETE_WINDOW_TYPE), [
+ argument('search', scalar('String')),
+ {...argument('offset', scalar('Int')), defaultValue: '0'},
+ {...argument('size', scalar('Int')), defaultValue: '2'}
+ ]),
field('validity', scalar('String'), [argument('name', scalar('String'))]),
field('datatype', scalar('String'))
])],
+ [GREET_AUTOCOMPLETE_WINDOW_TYPE, objectType(GREET_AUTOCOMPLETE_WINDOW_TYPE, [
+ field('items', list(scalar('String'))), field('offset', scalar('Int')),
+ field('requestedSize', scalar('Int')), field('returnedCount', scalar('Int')),
+ field('totalCount', scalar('Int')), field('maximumSize', scalar('Int')),
+ field('hasPrevious', scalar('Boolean')), field('hasNext', scalar('Boolean')),
+ field('ordering', scalar('String'))
+ ])],
[`${SAMPLE_SERVICE_TYPE}__greet__gqlv_action_invoke`, invokeType(
`${SAMPLE_SERVICE_TYPE}__greet__gqlv_action_invoke`, scalar('String')
)],
@@ -189,6 +204,16 @@ export function createMenuGraphQLExecutor({
datatype: 'String'
}}}}}}};
}
+ if (request.operationName === 'CausewayServiceActionParameterAutoCompleteWindow') {
+ serviceCalls.push(request);
+ return {data: {rich: {[SAMPLE_SERVICE_FIELD]: {greet: {params: {name: {
+ autoCompleteWindow: {
+ items: ['Grace'], offset: 2, requestedSize: 2, returnedCount: 1,
+ totalCount: 3, maximumSize: 2, hasPrevious: true, hasNext: false,
+ ordering: 'APPLICATION'
+ }
+ }}}}}}};
+ }
if (request.operationName === 'CausewayValidateServiceAction') {
serviceCalls.push(request);
const value = Object.values(request.variables)[0];
diff --git a/viewers/webcomponents/foundation/test/fixtures/rich-schema-fixture.mjs b/viewers/webcomponents/foundation/test/fixtures/rich-schema-fixture.mjs
index da0232819d2..dd108d56b98 100644
--- a/viewers/webcomponents/foundation/test/fixtures/rich-schema-fixture.mjs
+++ b/viewers/webcomponents/foundation/test/fixtures/rich-schema-fixture.mjs
@@ -37,6 +37,9 @@ const EMPTY_COLLECTION_TYPE = `${OBJECT_TYPE}__formerStaff__gqlv_collection`;
const ACTION_TYPE = `${OBJECT_TYPE}__changeName__gqlv_action`;
const ACTION_PARAMS_TYPE = `${OBJECT_TYPE}__changeName__gqlv_action_params`;
const ACTION_PARAM_TYPE = `${OBJECT_TYPE}__changeName__newName__gqlv_action_parameter`;
+const AUTOCOMPLETE_WINDOW_ORDERING_TYPE = 'rich__gqlv_autocomplete_window_ordering';
+const CHAIR_AUTOCOMPLETE_WINDOW_TYPE = `${CHAIR_TYPE}_autocomplete_window`;
+const ACTION_PARAM_AUTOCOMPLETE_WINDOW_TYPE = `${ACTION_PARAM_TYPE}_autocomplete_window`;
const STAFF_OBJECT_TYPE = 'rich__university_staff_StaffMember';
const STAFF_META_TYPE = `${STAFF_OBJECT_TYPE}__gqlv_meta`;
const STAFF_NAME_TYPE = `${STAFF_OBJECT_TYPE}__name__gqlv_property`;
@@ -136,6 +139,50 @@ export function createRichSchemaTypes() {
]);
}
+export function createAutoCompleteWindowRichSchemaTypes() {
+ const types = createRichSchemaTypes();
+ const windowFields = () => [
+ field('items', null, list(named(STAFF_OBJECT_TYPE))),
+ field('offset', null, nonNull(scalar('Int'))),
+ field('requestedSize', null, nonNull(scalar('Int'))),
+ field('returnedCount', null, nonNull(scalar('Int'))),
+ field('totalCount', null, nonNull(scalar('Int'))),
+ field('maximumSize', null, nonNull(scalar('Int'))),
+ field('hasPrevious', null, nonNull(scalar('Boolean'))),
+ field('hasNext', null, nonNull(scalar('Boolean'))),
+ field('ordering', null, nonNull(enumeration(AUTOCOMPLETE_WINDOW_ORDERING_TYPE)))
+ ];
+ const windowArguments = [
+ argument('search', nonNull(scalar('String'))),
+ argument('offset', nonNull(scalar('Int')), {defaultValue: '0'}),
+ argument('size', nonNull(scalar('Int')), {defaultValue: '5'})
+ ];
+ const chairType = types.get(CHAIR_TYPE);
+ types.set(CHAIR_TYPE, objectType(CHAIR_TYPE, null, [
+ ...chairType.fields,
+ field('autoComplete', null, list(named(STAFF_OBJECT_TYPE)), [argument('search', nonNull(scalar('String')))]),
+ field('autoCompleteWindow', null, named(CHAIR_AUTOCOMPLETE_WINDOW_TYPE), windowArguments)
+ ]));
+ const parameterType = types.get(ACTION_PARAM_TYPE);
+ types.set(ACTION_PARAM_TYPE, objectType(ACTION_PARAM_TYPE, null, [
+ ...parameterType.fields,
+ field('autoComplete', null, list(named(STAFF_OBJECT_TYPE)), [argument('search', nonNull(scalar('String')))]),
+ field('autoCompleteWindow', null, named(ACTION_PARAM_AUTOCOMPLETE_WINDOW_TYPE), [
+ argument('preceding', scalar('String')),
+ ...windowArguments
+ ])
+ ]));
+ types.set(CHAIR_AUTOCOMPLETE_WINDOW_TYPE, objectType(
+ CHAIR_AUTOCOMPLETE_WINDOW_TYPE, null, windowFields()));
+ types.set(ACTION_PARAM_AUTOCOMPLETE_WINDOW_TYPE, objectType(
+ ACTION_PARAM_AUTOCOMPLETE_WINDOW_TYPE, null, windowFields()));
+ types.set(AUTOCOMPLETE_WINDOW_ORDERING_TYPE, {
+ kind: 'ENUM', name: AUTOCOMPLETE_WINDOW_ORDERING_TYPE, description: null,
+ fields: [], enumValues: [{name: 'APPLICATION', description: null}], possibleTypes: []
+ });
+ return types;
+}
+
export function createVersionlessRichSchemaTypes({windowed = false} = {}) {
const types = windowed ? createWindowedRichSchemaTypes() : createRichSchemaTypes();
const metadataType = types.get(STAFF_META_TYPE);
diff --git a/viewers/webcomponents/foundation/test/graphql-client.test.mjs b/viewers/webcomponents/foundation/test/graphql-client.test.mjs
index 76ef647ad84..d6e87e17a92 100644
--- a/viewers/webcomponents/foundation/test/graphql-client.test.mjs
+++ b/viewers/webcomponents/foundation/test/graphql-client.test.mjs
@@ -23,6 +23,7 @@ import {CausewayGraphQLClient, CausewaySchemaError} from '../src/graphql-client.
import {RichSchemaNames} from '../src/schema-names.mjs';
import {
collectionWindowResponse,
+ createAutoCompleteWindowRichSchemaTypes,
createRichSchemaFixtureExecutor,
createRichSchemaTypes,
createWindowedRichSchemaTypes,
@@ -76,6 +77,25 @@ test('targeted introspection discovers object-valued action choices and their me
assert.equal(executor.introspectionCalls.every(call => Object.keys(call.variables).length === 1), true);
});
+test('autocomplete window discovery follows result item and metadata types', async () => {
+ const types = createAutoCompleteWindowRichSchemaTypes();
+ const executor = createRichSchemaFixtureExecutor({types});
+ const client = new CausewayGraphQLClient({executor});
+
+ const description = await client.describeObject(DEPARTMENT_LOGICAL_TYPE);
+
+ const propertyField = description.members.get('chair').fields.get('autoCompleteWindow');
+ const resultTypeName = propertyField.type.name;
+ assert.equal(description.types.has(resultTypeName), true);
+ const resultType = description.types.get(resultTypeName);
+ assert.equal(resultType.fields.some(field => field.name === 'items'), true);
+ assert.equal(description.types.has('rich__university_staff_StaffMember'), true);
+ assert.equal(description.types.has('rich__university_staff_StaffMember__gqlv_meta'), true);
+ const parameterType = description.types.get(
+ 'rich__university_dept_Department__changeName__newName__gqlv_action_parameter');
+ assert.equal(parameterType.fields.some(field => field.name === 'autoCompleteWindow'), true);
+});
+
test('targeted introspection discovers and executes bounded collection windows', async () => {
const rows = [{
_meta: {id: 'staff-1', logicalTypeName: 'university.staff.StaffMember', title: 'Dr Ada', version: '1'}
diff --git a/viewers/webcomponents/foundation/test/interaction-command.test.mjs b/viewers/webcomponents/foundation/test/interaction-command.test.mjs
index 8538cff5d5d..ee57671225a 100644
--- a/viewers/webcomponents/foundation/test/interaction-command.test.mjs
+++ b/viewers/webcomponents/foundation/test/interaction-command.test.mjs
@@ -155,6 +155,65 @@ test('object context executes property validation and update through semantic co
context.disconnect();
});
+test('object context prefers property autocomplete windows and normalizes metadata', async () => {
+ const description = fixtureDescription();
+ const choiceTypeName = 'rich__example_Choice';
+ const metadataTypeName = `${choiceTypeName}__gqlv_meta`;
+ const windowTypeName = `${description.generatedTypeName}__name__gqlv_property_autocomplete_window`;
+ const originalProperty = description.members.get('name');
+ const windowField = field('autoCompleteWindow', named(windowTypeName), [
+ {...argument('search', scalar('String')), defaultValue: null},
+ {...argument('offset', scalar('Int')), defaultValue: '0'},
+ {...argument('size', scalar('Int')), defaultValue: '5'}
+ ]);
+ const windowedDescription = {
+ ...description,
+ members: new Map(description.members).set('name', {
+ ...originalProperty,
+ fields: new Map(originalProperty.fields)
+ .set('autoComplete', field('autoComplete', list(named(choiceTypeName)), [argument('search', scalar('String'))]))
+ .set('autoCompleteWindow', windowField)
+ }),
+ types: new Map([
+ ...description.types,
+ [windowTypeName, graphType(windowTypeName, [
+ field('items', list(named(choiceTypeName))), field('offset', scalar('Int')),
+ field('requestedSize', scalar('Int')), field('returnedCount', scalar('Int')),
+ field('totalCount', scalar('Int')), field('maximumSize', scalar('Int')),
+ field('hasPrevious', scalar('Boolean')), field('hasNext', scalar('Boolean')),
+ field('ordering', scalar('String'))
+ ])],
+ [choiceTypeName, graphType(choiceTypeName, [field('_meta', named(metadataTypeName))])],
+ [metadataTypeName, graphType(metadataTypeName, [
+ field('id', scalar('ID')), field('logicalTypeName', scalar('String')), field('title', scalar('String'))
+ ])]
+ ])
+ };
+ const choice = {_meta: {id: 'choice-6', logicalTypeName: 'example.Choice', title: 'Choice 6'}};
+ let request;
+ const client = {
+ describeObject: async () => windowedDescription,
+ executeObjectInteraction: async candidate => {
+ request = candidate;
+ return {data: {name: {autoCompleteWindow: {
+ items: [choice], offset: 5, requestedSize: 5, returnedCount: 1, totalCount: 6,
+ maximumSize: 5, hasPrevious: true, hasNext: false, ordering: 'APPLICATION'
+ }}}, errors: [], operation: {operationName: candidate.operationName}};
+ }
+ };
+ const context = new ObjectContextController({client, logicalTypeName: 'example.Object', objectId: '42'});
+
+ const result = await context.autoCompletePropertyWindow('name', 'Choice', {offset: 5, size: 5});
+
+ assert.equal(result.status, 'success');
+ assert.equal(result.data.windowed, true);
+ assert.deepEqual(result.data.items, [choice]);
+ assert.equal(result.data.totalCount, 6);
+ assert.match(JSON.stringify(request.selection), /autoCompleteWindow/);
+ assert.deepEqual(request.selection.name.autoCompleteWindow.__args, {search: 'Choice', offset: 5, size: 5});
+ context.disconnect();
+});
+
test('query-only and non-compliant variants report or execute discovered capabilities', async () => {
const description = fixtureDescription();
const queryOnlyClient = {
@@ -222,6 +281,56 @@ test('versionless preparation and autocomplete select only advertised identity m
context.disconnect();
});
+test('action parameter autocomplete windows preserve declared dependent arguments', async () => {
+ const description = versionlessPreparationDescription();
+ const parameterTypeName = `${description.generatedTypeName}__choose__choice__gqlv_action_parameter`;
+ const windowTypeName = `${parameterTypeName}_autocomplete_window`;
+ const parameterType = description.types.get(parameterTypeName);
+ const windowField = field('autoCompleteWindow', named(windowTypeName), [
+ argument('preceding', scalar('String')), argument('search', scalar('String')),
+ {...argument('offset', scalar('Int')), defaultValue: '0'},
+ {...argument('size', scalar('Int')), defaultValue: '5'}
+ ]);
+ description.types.set(parameterTypeName, graphType(parameterTypeName, [
+ ...parameterType.fields, windowField
+ ]));
+ const action = description.members.get('choose');
+ const paramsTypeName = `${description.generatedTypeName}__choose__gqlv_action_params`;
+ description.types.set(paramsTypeName, graphType(paramsTypeName, [field('choice', named(parameterTypeName))]));
+ description.types.set(windowTypeName, graphType(windowTypeName, [
+ field('items', list(named('rich__example_VersionlessChoice'))),
+ field('offset', scalar('Int')), field('requestedSize', scalar('Int')),
+ field('returnedCount', scalar('Int')), field('totalCount', scalar('Int')),
+ field('maximumSize', scalar('Int')), field('hasPrevious', scalar('Boolean')),
+ field('hasNext', scalar('Boolean')), field('ordering', scalar('String'))
+ ]));
+ description.members.set('choose', {...action});
+ const choice = {_meta: {id: 'choice-6', logicalTypeName: 'example.VersionlessChoice', title: 'Choice six'}};
+ let request;
+ const client = {
+ describeObject: async () => description,
+ describeMutation: async () => null,
+ executeObjectInteraction: async candidate => {
+ request = candidate;
+ return {data: {choose: {params: {choice: {autoCompleteWindow: {
+ items: [choice], offset: 5, requestedSize: 5, returnedCount: 1, totalCount: 6,
+ maximumSize: 5, hasPrevious: true, hasNext: false, ordering: 'APPLICATION'
+ }}}}}, errors: [], operation: {}};
+ }
+ };
+ const context = new ObjectContextController({client, logicalTypeName: 'example.Object', objectId: '42'});
+
+ const result = await context.autoCompleteActionParameterWindow(
+ 'choose', 'choice', 'Cho', {preceding: 'current', ignored: 'omit'}, {offset: 5, size: 5});
+
+ assert.equal(result.status, 'success');
+ assert.equal(result.data.items[0]._meta.id, 'choice-6');
+ assert.deepEqual(request.selection.choose.params.choice.autoCompleteWindow.__args, {
+ preceding: 'current', search: 'Cho', offset: 5, size: 5
+ });
+ context.disconnect();
+});
+
test('broad abstract mutation outcomes execute once and remain typename-only', async () => {
const description = fixtureDescription();
const unionTypeName = 'rich__example_BroadResultUnion';
diff --git a/viewers/webcomponents/foundation/test/interaction.test.mjs b/viewers/webcomponents/foundation/test/interaction.test.mjs
index 6a9532eef41..7599c35d042 100644
--- a/viewers/webcomponents/foundation/test/interaction.test.mjs
+++ b/viewers/webcomponents/foundation/test/interaction.test.mjs
@@ -26,12 +26,15 @@ const {
CausewayEditorRegistry,
CausewayInteractionControllerElement,
CausewayPropertyElement,
+ CausewayReferenceEditorElement,
InteractionStatus,
+ autoCompleteWindowPlan,
buildMutationInteractionOperation,
buildObjectInteractionOperation,
commandSelection,
configureCausewayReferenceWidgets,
defaultEditorRegistry,
+ normalizeAutoCompleteWindow,
parseCausewayEditorValue,
renderCausewayEditor
} = await import('../src/index.mjs');
@@ -126,6 +129,37 @@ test('interaction operations render and validate inline fragments', () => {
}), /not advertised/);
});
+test('autocomplete windows derive advertised selections and normalize paging metadata', () => {
+ const itemType = type('Choice', [field('_meta', named('ChoiceMeta'))]);
+ const metadataType = type('ChoiceMeta', [field('id', scalar('ID')), field('logicalTypeName', scalar('String'))]);
+ const windowType = type('ChoiceWindow', [
+ field('items', list(named('Choice'))), field('offset', scalar('Int')),
+ field('requestedSize', scalar('Int')), field('returnedCount', scalar('Int')),
+ field('totalCount', scalar('Int')), field('maximumSize', scalar('Int')),
+ field('hasPrevious', scalar('Boolean')), field('hasNext', scalar('Boolean')),
+ field('ordering', scalar('String'))
+ ]);
+ const windowField = field('autoCompleteWindow', named('ChoiceWindow'), [
+ {...argument('offset', scalar('Int')), defaultValue: '0'},
+ {...argument('size', scalar('Int')), defaultValue: '5'}
+ ]);
+ const plan = autoCompleteWindowPlan(windowField, new Map([
+ ['ChoiceWindow', windowType], ['Choice', itemType], ['ChoiceMeta', metadataType]
+ ]));
+
+ assert.equal(plan.offsetDefault, 0);
+ assert.equal(plan.sizeDefault, 5);
+ assert.deepEqual(plan.selection.items, {_meta: {id: true, logicalTypeName: true}});
+ const normalized = normalizeAutoCompleteWindow({
+ items: [{_meta: {id: '6', logicalTypeName: 'example.Choice'}}], offset: 5,
+ requestedSize: 5, returnedCount: 1, totalCount: 6, maximumSize: 5,
+ hasPrevious: true, hasNext: false, ordering: 'APPLICATION'
+ });
+ assert.equal(normalized.windowed, true);
+ assert.equal(normalized.totalCount, 6);
+ assert.equal(normalized.items.length, 1);
+});
+
test('editor registry selects standard inputs and supports application overrides', () => {
const text = renderCausewayEditor({
name: 'name', value: 'Classics', choices: [], enumValues: [], inputType: scalar('String'),
@@ -366,6 +400,100 @@ test('editable properties support prepare, validation, cancel and authoritative
assert.equal(calls.includes('update:Cancelled'), false);
});
+test('windowed Vaadin reference adapter requests authoritative later pages', async () => {
+ const moduleSource = `
+ if (!globalThis.customElements.get('vaadin-combo-box')) globalThis.customElements.define('vaadin-combo-box', class extends HTMLElement {});
+ if (!globalThis.customElements.get('vaadin-multi-select-combo-box')) globalThis.customElements.define('vaadin-multi-select-combo-box', class extends HTMLElement {});
+ `;
+ globalThis.customElements.whenDefined ??= async () => {};
+ configureCausewayReferenceWidgets({
+ enabled: true,
+ minimumSearchLength: 1,
+ maximumResults: 50,
+ moduleUrl: `data:text/javascript,${encodeURIComponent(moduleSource)}`
+ });
+ const editor = new CausewayReferenceEditorElement();
+ editor.dataset ??= {};
+ editor.childNodes ??= [];
+ editor.replaceChildren = (...children) => {
+ editor.childNodes = children;
+ for (const child of children) child.parentNode = editor;
+ };
+ editor.id = 'owner-editor';
+ editor.setAttribute('data-causeway-editor', 'owner');
+ editor.setAttribute('data-label', 'Owner');
+ editor.setAttribute('data-items', '[]');
+ editor.setAttribute('data-value', 'null');
+ editor.setAttribute('data-autocomplete', 'true');
+ editor.setAttribute('data-autocomplete-window', 'true');
+ editor.setAttribute('data-autocomplete-page-size', '2');
+ Object.assign(editor.dataset, {
+ autocomplete: 'true',
+ autocompleteWindow: 'true',
+ autocompletePageSize: '2',
+ items: '[]',
+ value: 'null',
+ label: 'Owner'
+ });
+ let requested;
+ const pendingRequests = new Map();
+ editor.addEventListener('causeway-reference-search', event => {
+ requested = event.detail;
+ pendingRequests.set(event.detail.search, event.detail);
+ if (event.detail.search === 'Ow') {
+ event.detail.respond({
+ status: 'success',
+ data: {
+ items: [{_meta: {id: 'owner-3', logicalTypeName: 'example.Owner', title: 'Owner 3'}}],
+ offset: 2,
+ requestedSize: 2,
+ returnedCount: 1,
+ totalCount: 3,
+ maximumSize: 2,
+ hasPrevious: true,
+ hasNext: false,
+ ordering: 'APPLICATION',
+ windowed: true
+ }
+ });
+ }
+ });
+ document.body.appendChild(editor);
+ for (let index = 0; index < 20 && editor.dataset.widgetState !== 'ready'; index += 1) {
+ await new Promise(resolve => setTimeout(resolve, 0));
+ }
+ assert.equal(editor.dataset.widgetState, 'ready', editor.dataset.widgetError);
+ const control = editor.childNodes[0];
+ assert.equal(control.pageSize, 2);
+ let callbackResult;
+
+ control.dataProvider({filter: 'Ow', page: 1, pageSize: 2}, (items, total) => {
+ callbackResult = {items, total};
+ });
+ await new Promise(resolve => setTimeout(resolve, 0));
+
+ assert.equal(requested.offset, 2);
+ assert.equal(requested.size, 2);
+ assert.deepEqual(callbackResult, {
+ items: [{id: 'owner-3', logicalTypeName: 'example.Owner', title: 'Owner 3'}],
+ total: 3
+ });
+
+ let staleCallback;
+ let currentCallback;
+ control.dataProvider({filter: 'Old', page: 0, pageSize: 2}, (items, total) => staleCallback = {items, total});
+ control.dataProvider({filter: 'New', page: 0, pageSize: 2}, (items, total) => currentCallback = {items, total});
+ pendingRequests.get('Old').respond({status: 'success', data: {
+ items: [{_meta: {id: 'old', title: 'Old'}}], totalCount: 1, windowed: true
+ }});
+ pendingRequests.get('New').respond({status: 'success', data: {
+ items: [{_meta: {id: 'new', title: 'New'}}], totalCount: 1, windowed: true
+ }});
+ assert.equal(staleCallback, undefined);
+ assert.deepEqual(currentCallback, {items: [{id: 'new', title: 'New'}], total: 1});
+ document.body.removeChild(editor);
+});
+
test('reference autocomplete cancels stale work and rejects over-bound results', async () => {
configureCausewayReferenceWidgets({enabled: true, minimumSearchLength: 2, maximumResults: 2});
let stateListener;
diff --git a/viewers/webcomponents/htmx/README.adoc b/viewers/webcomponents/htmx/README.adoc
index 28b51698046..a626efafc01 100644
--- a/viewers/webcomponents/htmx/README.adoc
+++ b/viewers/webcomponents/htmx/README.adoc
@@ -26,7 +26,8 @@ The shell uses external same-origin scripts and styles and requires no inline sc
`causeway.viewer.webcomponents.htmx.wicket-comparison-path` optionally adds a footer link and is intended only for comparison samples.
`causeway.viewer.webcomponents.htmx.vaadin-reference-widgets` defaults to `false` and explicitly enables the internal free-core reference-widget pilot.
`causeway.viewer.webcomponents.htmx.reference-minimum-search-length` defaults to `2`.
-`causeway.viewer.webcomponents.htmx.reference-maximum-results` defaults to `50` and bounds one complete search-only GraphQL autocomplete response; it is not a server page size.
+`causeway.viewer.webcomponents.htmx.reference-maximum-results` defaults to `50` and is the requested page-size fallback for advertised GraphQL autocomplete windows as well as the accepted complete-response bound for legacy non-windowed autocomplete.
+An advertised field's smaller introspected default window size takes precedence.
The complete shell applies a restrictive same-origin content-security policy and returns `private, no-store`.
The default policy and asset requests remain unchanged while the pilot is disabled.
diff --git a/viewers/webcomponents/sample-htmx-petclinic/src/playwright/java/org/apache/causeway/viewer/webcomponents/sample/htmx/petclinic/PetClinicHtmxPlaywrightTest.java b/viewers/webcomponents/sample-htmx-petclinic/src/playwright/java/org/apache/causeway/viewer/webcomponents/sample/htmx/petclinic/PetClinicHtmxPlaywrightTest.java
index f2f08454684..f90b2f178ff 100644
--- a/viewers/webcomponents/sample-htmx-petclinic/src/playwright/java/org/apache/causeway/viewer/webcomponents/sample/htmx/petclinic/PetClinicHtmxPlaywrightTest.java
+++ b/viewers/webcomponents/sample-htmx-petclinic/src/playwright/java/org/apache/causeway/viewer/webcomponents/sample/htmx/petclinic/PetClinicHtmxPlaywrightTest.java
@@ -361,8 +361,14 @@ void disposableOwnerExercisesCreateAndEveryObjectAction() {
throw new AssertionError(String.valueOf(
page.locator(PROMPT).evaluate("element => element.outerHTML")), cause);
}
- page.waitForFunction("selector => document.querySelector(selector)?.dataset.widgetState === 'ready'", parameter("pet"));
- assertThat(petReference.evaluate("element => element.value?.id")).isNotNull();
+ if (Boolean.TRUE.equals(petReference.evaluate("element => element.localName === 'select'"))) {
+ petReference.evaluate("element => { element.selectedIndex = 0; "
+ + "element.dispatchEvent(new Event('change', {bubbles: true, composed: true})); }");
+ assertThat(petReference.inputValue()).isNotBlank();
+ } else {
+ page.waitForFunction("selector => document.querySelector(selector)?.dataset.widgetState === 'ready'", parameter("pet"));
+ assertThat(petReference.evaluate("element => element.value?.id")).isNotNull();
+ }
assertThat(page.locator(parameter("visitAt")).count())
.as(page.locator(PROMPT).evaluate("element => element.outerHTML").toString())
.isEqualTo(1);