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/09/02 03:39:38 UTC
(causeway) 02/06: feat(webcomponents): add standalone collection results
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 82f69760e707b60f923ab68345cf3490fe4dcb50
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Tue Sep 1 19:12:26 2026 +0200
feat(webcomponents): add standalone collection results
---
.../add-standalone-collection-component/tasks.md | 34 +-
viewers/webcomponents/foundation/USAGE.adoc | 35 +-
.../foundation/src/component-contracts.mjs | 2 +
.../foundation/src/component-styles.css | 7 +-
.../foundation/src/component-styles.mjs | 7 +-
viewers/webcomponents/foundation/src/index.mjs | 1 +
viewers/webcomponents/foundation/src/register.mjs | 6 +
.../src/standalone-collection-element.mjs | 524 +++++++++++++++++++++
viewers/webcomponents/foundation/src/theme.css | 6 +
.../foundation/test/domain-components.test.mjs | 1 +
.../foundation/test/element-prefix.test.mjs | 4 +-
.../foundation/test/standalone-collection.test.mjs | 208 ++++++++
.../resources/causeway-htmx/causeway-htmx.css | 4 -
.../resources/causeway-htmx/causeway-htmx.mjs | 25 +-
.../petclinic/PetClinicHtmxPlaywrightTest.java | 65 ++-
15 files changed, 872 insertions(+), 57 deletions(-)
diff --git a/openspec/changes/add-standalone-collection-component/tasks.md b/openspec/changes/add-standalone-collection-component/tasks.md
index 195fa0b2bea..7713b420fe7 100644
--- a/openspec/changes/add-standalone-collection-component/tasks.md
+++ b/openspec/changes/add-standalone-collection-component/tasks.md
@@ -1,31 +1,31 @@
## 1. Public standalone collection contract
-- [ ] 1.1 Add the standalone collection element and host vocabulary to public contracts, exports, registration, prefix checks, and pre-upgrade declaration capture.
-- [ ] 1.2 Implement the property-only normalized result contract, generation-safe replacement, bounded idle, ready, empty, unsupported, and collection-state event lifecycle.
-- [ ] 1.3 Preserve direct-child column declarations and presentation attributes without accepting member loading, paging, sorting, filtering, activation, or associated actions.
-- [ ] 1.4 Add component contract and lifecycle tests for property assignment, replacement, invalid shapes, events, registration, and declaration node identity.
+- [x] 1.1 Add the standalone collection element and host vocabulary to public contracts, exports, registration, prefix checks, and pre-upgrade declaration capture.
+- [x] 1.2 Implement the property-only normalized result contract, generation-safe replacement, bounded idle, ready, empty, unsupported, and collection-state event lifecycle.
+- [x] 1.3 Preserve direct-child column declarations and presentation attributes without accepting member loading, paging, sorting, filtering, activation, or associated actions.
+- [x] 1.4 Add component contract and lifecycle tests for property assignment, replacement, invalid shapes, events, registration, and declaration node identity.
## 2. Native semantic result presentation
-- [ ] 2.1 Render authoritative object metadata through semantic object links and scalar rows through the standard value-renderer registry.
-- [ ] 2.2 Render supplied declared-column wrappers through shared collection cell semantics and expose unavailable cells without follow-up requests.
-- [ ] 2.3 Add accessible heading, description, empty, unsupported, error, responsive list and table styling with deterministic test hooks.
-- [ ] 2.4 Add Foundation tests for object, icon, scalar, null, hidden, disabled, error, missing-column, escaping, navigation, and native fallback behavior.
+- [x] 2.1 Render authoritative object metadata through semantic object links and scalar rows through the standard value-renderer registry.
+- [x] 2.2 Render supplied declared-column wrappers through shared collection cell semantics and expose unavailable cells without follow-up requests.
+- [x] 2.3 Add accessible heading, description, empty, unsupported, error, responsive list and table styling with deterministic test hooks.
+- [x] 2.4 Add Foundation tests for object, icon, scalar, null, hidden, disabled, error, missing-column, escaping, navigation, and native fallback behavior.
## 3. Finite Grid qualification
-- [ ] 3.1 Project complete standalone snapshots through existing collection Grid projection and qualification without a member range broker.
-- [ ] 3.2 Supply authoritative array totals and a generation-safe static range provider while omitting paging, sorting, filtering, hydration, and server range callbacks.
-- [ ] 3.3 Preserve resizable and reorderable presentation, small-result sizing, native fallback, adapter failure, disconnect, and replacement lifecycle.
-- [ ] 3.4 Extend Grid unit and browser audits for qualified, narrow, native, unsupported, superseded, and diagnostic-clean standalone results.
+- [x] 3.1 Project complete standalone snapshots through existing collection Grid projection and qualification without a member range broker.
+- [x] 3.2 Supply authoritative array totals and a generation-safe static range provider while omitting paging, sorting, filtering, hydration, and server range callbacks.
+- [x] 3.3 Preserve resizable and reorderable presentation, small-result sizing, native fallback, adapter failure, disconnect, and replacement lifecycle.
+- [x] 3.4 Extend Grid unit and browser audits for qualified, narrow, native, unsupported, superseded, and diagnostic-clean standalone results.
## 4. HTMX action-result integration
-- [ ] 4.1 Replace the viewer-owned collection result list with one `<cw-standalone-collection>` assigned from the unchanged semantic action result.
-- [ ] 4.2 Preserve application result overrides, object navigation, scalar and void handling, announcements, controller dismissal, result replacement, and route lifecycle.
-- [ ] 4.3 Extend HTMX JavaScript tests and Petclinic Playwright journeys for service collection results, authoritative links and icons, canonical navigation, focus, default Vaadin, and explicit native policies.
+- [x] 4.1 Replace the viewer-owned collection result list with one `<cw-standalone-collection>` assigned from the unchanged semantic action result.
+- [x] 4.2 Preserve application result overrides, object navigation, scalar and void handling, announcements, controller dismissal, result replacement, and route lifecycle.
+- [x] 4.3 Extend HTMX JavaScript tests and Petclinic Playwright journeys for service collection results, authoritative links and icons, canonical navigation, focus, default Vaadin, and explicit native policies.
## 5. Documentation and validation
-- [ ] 5.1 Document standalone collection markup, property assignment, supported presentation, lifecycle events, and deliberate member-feature exclusions.
-- [ ] 5.2 Run complete Foundation Node and Maven suites, Grid and field browser audits, Petclinic integration and Playwright tests, IDE validation, strict OpenSpec validation, and final diff checks.
+- [x] 5.1 Document standalone collection markup, property assignment, supported presentation, lifecycle events, and deliberate member-feature exclusions.
+- [x] 5.2 Run complete Foundation Node and Maven suites, Grid and field browser audits, Petclinic integration and Playwright tests, IDE validation, strict OpenSpec validation, and final diff checks.
diff --git a/viewers/webcomponents/foundation/USAGE.adoc b/viewers/webcomponents/foundation/USAGE.adoc
index 7abfb623f35..9ea37d86fe6 100644
--- a/viewers/webcomponents/foundation/USAGE.adoc
+++ b/viewers/webcomponents/foundation/USAGE.adoc
@@ -50,7 +50,7 @@ The collection remains inactive until its load button is selected or its `active
== Public component contract
-The public vocabulary consists of `cw-graphql-client`, `cw-menubars`, `cw-menubar-primary`, `cw-menubar-secondary`, `cw-menubar-tertiary`, `cw-object-context`, `cw-object`, `cw-object-header`, `cw-breadcrumbs`, `cw-property`, `cw-value`, `cw-object-link`, `cw-action`, `cw-interaction-controller`, `cw-field-editor`, `cw-reference-editor`, `cw-collection`, and `cw-collection-column`.
+The public vocabulary consists of `cw-graphql-client`, `cw-menubars`, `cw-menubar-primary`, `cw-menubar-secondary`, `cw-menubar-tertiary`, `cw-object-context`, `cw-object`, `cw-object-header`, `cw-breadcrumbs`, `cw-property`, `cw-value`, `cw-object-link`, `cw-action`, `cw-interaction-controller`, `cw-field-editor`, `cw-reference-editor`, `cw-collection`, `cw-standalone-collection`, and `cw-collection-column`.
`CausewayElementName`, `CausewayAttribute`, `CausewayHostClass`, and `CausewaySemanticEvent` export the stable names used by the implementation.
The `cw-` element namespace replaces the former `causeway-` element namespace without compatibility aliases.
@@ -576,6 +576,39 @@ Direct compositions expose `data-causeway-associated-member`, `data-causeway-act
Use `--causeway-associated-action-gap` and `--causeway-associated-action-margin-block-end` to adjust wrapping presentation without inline styles or toolkit-specific elements.
Generated `<cw-object>` layouts retain semantically equivalent associated-member and action-group hooks from effective grid XML.
+== Standalone action-result collections
+
+`<cw-standalone-collection>` presents a normalized collection-valued action result without pretending that the result is an object member.
+A host assigns the established result object through the JavaScript-only `result` property:
+
+[source,javascript]
+----
+const collection = document.querySelector('cw-standalone-collection');
+collection.result = actionResultDetail.result;
+----
+
+[source,html]
+----
+<cw-standalone-collection named="Matching owners" described-as="Owners returned by the action"
+ description-as="tooltip" resizable-columns reorderable-columns>
+ <cw-collection-column id="name" label="Name"></cw-collection-column>
+</cw-standalone-collection>
+----
+
+The accepted shape is `{kind: "collection", value: [...]}` and is never reflected to an attribute or serialized into authored markup.
+Replacing `result` atomically retires the prior generation; assigning `null` produces the idle state, an empty array produces `No items`, and malformed or non-collection shapes produce a bounded unsupported state.
+The component emits `causeway-collection-state-change` with `standalone: true`, a null member, the current generation, and its immutable result state.
+
+Rows with authoritative `_meta.logicalTypeName` and `_meta.id` render semantic object links using the advertised title and optional icon.
+Supported scalar rows use the standard value-renderer registry without invented identity.
+Direct-child `<cw-collection-column>` declarations render only wrappers or values already present in the action result; an absent value is explicitly unavailable and never causes a follow-up read.
+Column declaration order and node identity survive component rerendering.
+
+The component owns no object context, member id, row hydration, associated action, activation, GraphQL load, paging, sorting, filtering, editing, or mutation capability.
+Attributes that would imply those member-only capabilities are inert.
+At wide widths, a complete object-valued snapshot may qualify for the internal Grid using the authoritative array length and a static generation-safe range provider; narrow, native-policy, unsupported, or failed qualification uses the accessible native list or table.
+Applications must not consume the internal Grid tag, projection objects, or range callback.
+
== Lazy collections and row hydration
A collection's primary object requirement contains advertised `hidden` and `disabled` state plus supported canonical `metadata.friendlyName` and `metadata.description` heading fields.
diff --git a/viewers/webcomponents/foundation/src/component-contracts.mjs b/viewers/webcomponents/foundation/src/component-contracts.mjs
index a8415ceae0b..8ebb71f3629 100644
--- a/viewers/webcomponents/foundation/src/component-contracts.mjs
+++ b/viewers/webcomponents/foundation/src/component-contracts.mjs
@@ -34,6 +34,7 @@ export const CausewayElementName = Object.freeze({
INTERACTION_CONTROLLER: 'cw-interaction-controller',
REFERENCE_EDITOR: 'cw-reference-editor',
COLLECTION: 'cw-collection',
+ STANDALONE_COLLECTION: 'cw-standalone-collection',
COLLECTION_COLUMN: 'cw-collection-column',
MENUBARS: 'cw-menubars',
MENUBAR_PRIMARY: 'cw-menubar-primary',
@@ -58,6 +59,7 @@ export const CausewayHostClass = Object.freeze({
ACTION_RESULT: 'causeway-action-result',
PROPERTY_EDITOR: 'causeway-property-editor',
COLLECTION: 'causeway-collection',
+ STANDALONE_COLLECTION: 'causeway-standalone-collection',
COLLECTION_COLUMN: 'causeway-collection-column',
MENUBARS: 'causeway-menubars',
MENUBAR: 'causeway-menubar',
diff --git a/viewers/webcomponents/foundation/src/component-styles.css b/viewers/webcomponents/foundation/src/component-styles.css
index d81fdf5880e..f4b579f6eaf 100644
--- a/viewers/webcomponents/foundation/src/component-styles.css
+++ b/viewers/webcomponents/foundation/src/component-styles.css
@@ -575,7 +575,8 @@ cw-action-control > vaadin-button > .causeway-action-icon:last-child {
.causeway-value-null {
font-style: italic;
}
-cw-collection {
+cw-collection,
+cw-standalone-collection {
container-name: cw-collection;
container-type: inline-size;
display: block;
@@ -598,6 +599,10 @@ cw-collection-grid {
--vaadin-grid-row-hover-background-color: var(--causeway-surface-subtle, color-mix(in srgb, CanvasText 6%, Canvas));
--lumo-font-size-m: var(--causeway-font-size-sm, 0.82rem);
}
+.causeway-standalone-collection-count {
+ display: block;
+ padding-inline: var(--causeway-space-3, 0.75rem);
+}
.causeway-collection-content {
min-inline-size: 0;
padding-block: var(--causeway-collection-content-padding, 0.75rem);
diff --git a/viewers/webcomponents/foundation/src/component-styles.mjs b/viewers/webcomponents/foundation/src/component-styles.mjs
index a8ebee02b3e..c147993dfd9 100644
--- a/viewers/webcomponents/foundation/src/component-styles.mjs
+++ b/viewers/webcomponents/foundation/src/component-styles.mjs
@@ -576,7 +576,8 @@ cw-action-control > vaadin-button > .causeway-action-icon:last-child {
.causeway-value-null {
font-style: italic;
}
-cw-collection {
+cw-collection,
+cw-standalone-collection {
container-name: cw-collection;
container-type: inline-size;
display: block;
@@ -599,6 +600,10 @@ cw-collection-grid {
--vaadin-grid-row-hover-background-color: var(--causeway-surface-subtle, color-mix(in srgb, CanvasText 6%, Canvas));
--lumo-font-size-m: var(--causeway-font-size-sm, 0.82rem);
}
+.causeway-standalone-collection-count {
+ display: block;
+ padding-inline: var(--causeway-space-3, 0.75rem);
+}
.causeway-collection-content {
min-inline-size: 0;
padding-block: var(--causeway-collection-content-padding, 0.75rem);
diff --git a/viewers/webcomponents/foundation/src/index.mjs b/viewers/webcomponents/foundation/src/index.mjs
index 994c8240e64..c7680de6f25 100644
--- a/viewers/webcomponents/foundation/src/index.mjs
+++ b/viewers/webcomponents/foundation/src/index.mjs
@@ -22,6 +22,7 @@ export * from './action-widget.mjs';
export * from './breadcrumbs-element.mjs';
export * from './collection-column-element.mjs';
export * from './collection-element.mjs';
+export * from './standalone-collection-element.mjs';
export * from './collection-grid-projection.mjs';
export * from './collection-grid-qualification.mjs';
export * from './collection-range-broker.mjs';
diff --git a/viewers/webcomponents/foundation/src/register.mjs b/viewers/webcomponents/foundation/src/register.mjs
index fdf2f602ea8..abe0b717aaf 100644
--- a/viewers/webcomponents/foundation/src/register.mjs
+++ b/viewers/webcomponents/foundation/src/register.mjs
@@ -22,6 +22,10 @@ import {CausewayBreadcrumbsElement} from './breadcrumbs-element.mjs';
import {CAUSEWAY_ACTION_CONTROL, CausewayActionControlElement} from './action-widget.mjs';
import {CausewayCollectionColumnElement} from './collection-column-element.mjs';
import {captureDeclarativeCollectionColumns, CausewayCollectionElement} from './collection-element.mjs';
+import {
+ captureDeclarativeStandaloneCollectionColumns,
+ CausewayStandaloneCollectionElement
+} from './standalone-collection-element.mjs';
import {CausewayElementName} from './component-contracts.mjs';
import {CAUSEWAY_FIELD_EDITOR, CausewayFieldEditorElement} from './field-widget.mjs';
import {CausewayGraphQLClientElement} from './graphql-client-element.mjs';
@@ -65,6 +69,7 @@ const DEFINITIONS = Object.freeze([
[CAUSEWAY_MENUBAR_CONTROL, CausewayMenubarControlElement],
[CausewayElementName.COLLECTION_COLUMN, CausewayCollectionColumnElement],
[CausewayElementName.COLLECTION, CausewayCollectionElement],
+ [CausewayElementName.STANDALONE_COLLECTION, CausewayStandaloneCollectionElement],
[CAUSEWAY_COLLECTION_GRID, CausewayCollectionGridElement]
]);
@@ -74,6 +79,7 @@ export function defineCausewayWebComponents(registry = globalThis.customElements
}
captureDeclarativeActionParameters();
captureDeclarativeCollectionColumns();
+ captureDeclarativeStandaloneCollectionColumns();
for (const [name, constructor] of DEFINITIONS) {
if (!registry.get(name)) {
registry.define(name, constructor);
diff --git a/viewers/webcomponents/foundation/src/standalone-collection-element.mjs b/viewers/webcomponents/foundation/src/standalone-collection-element.mjs
new file mode 100644
index 00000000000..048af22fbfb
--- /dev/null
+++ b/viewers/webcomponents/foundation/src/standalone-collection-element.mjs
@@ -0,0 +1,524 @@
+/*
+ * 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
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import {buildCausewayGridProjection} from './collection-grid-projection.mjs';
+import {
+ publishCausewayGridDiagnostics,
+ qualifyCausewayCollectionGrid
+} from './collection-grid-qualification.mjs';
+import {CausewaySemanticEvent} from './component-contracts.mjs';
+import {createSemanticEvent} from './context-events.mjs';
+import {
+ DescriptionPresentation,
+ normalizeDescriptionPresentation
+} from './description-presentation.mjs';
+import {
+ CAUSEWAY_COLLECTION_GRID,
+ CAUSEWAY_GRID_WIDGET_POLICY_EVENT,
+ causewayGridWidgetConfiguration
+} from './grid-widget.mjs';
+import {escapeHtml} from './rendering.mjs';
+import {defaultValueRendererRegistry, renderCausewayValue} from './value-renderers.mjs';
+
+const HTMLElementBase = globalThis.HTMLElement ?? class extends EventTarget {};
+const initialColumnConfigurations = new WeakMap();
+let standaloneCollectionSequence = 0;
+
+export function captureDeclarativeStandaloneCollectionColumns(root = globalThis.document) {
+ if (!root?.querySelectorAll) return;
+ const collections = root.localName === 'cw-standalone-collection'
+ ? [root]
+ : root.querySelectorAll('cw-standalone-collection');
+ for (const collection of collections) {
+ const columns = declarativeColumns(collection);
+ if (columns.length > 0) initialColumnConfigurations.set(collection, columns);
+ }
+}
+
+export class CausewayStandaloneCollectionElement extends HTMLElementBase {
+ static get observedAttributes() {
+ return ['named', 'described-as', 'description-as', 'resizable-columns', 'reorderable-columns'];
+ }
+
+ constructor() {
+ super();
+ const sequence = ++standaloneCollectionSequence;
+ this.labelId = `causeway-standalone-collection-label-${sequence}`;
+ this.descriptionId = `causeway-standalone-collection-description-${sequence}`;
+ this._result = null;
+ this._columns = [];
+ this._rendererRegistry = defaultValueRendererRegistry;
+ this.resultState = frozenState('idle');
+ this.resultGeneration = 0;
+ this.connectionStarted = false;
+ this.gridHostRevision = 0;
+ this.gridResponsiveRevision = 0;
+ this.gridResizeRevision = 0;
+ this._gridWide = false;
+ this._gridProjection = buildCausewayGridProjection();
+ this._gridQualification = qualifyCausewayCollectionGrid();
+ this.gridPolicyListener = () => {
+ this.gridHostRevision += 1;
+ this.render();
+ };
+ this.gridResizeObserver = typeof globalThis.ResizeObserver === 'function'
+ ? new ResizeObserver(entries => {
+ const width = entries.at(-1)?.contentRect?.width;
+ if (!Number.isFinite(width)) return;
+ const revision = ++this.gridResizeRevision;
+ const apply = () => {
+ if (this.isConnected && revision === this.gridResizeRevision) {
+ this.acceptGridResponsiveState(width > collectionBreakpointPixels());
+ }
+ };
+ if (typeof globalThis.requestAnimationFrame === 'function') globalThis.requestAnimationFrame(apply);
+ else queueMicrotask(apply);
+ })
+ : null;
+ this.columnObserver = typeof globalThis.MutationObserver === 'function'
+ ? new MutationObserver(records => {
+ if (records.some(record => [...(record.addedNodes ?? []), ...(record.removedNodes ?? [])]
+ .some(node => node?.localName === 'cw-collection-column'))) {
+ this.#captureColumns({replace: true});
+ this.gridHostRevision += 1;
+ this.render();
+ }
+ })
+ : null;
+ this.addEventListener(CausewaySemanticEvent.COLLECTION_CONFIGURATION, event => {
+ if (event.target?.parentNode !== this) return;
+ this.#acceptColumn(event.detail?.column);
+ });
+ }
+
+ get named() {
+ return this.getAttribute('named') || '';
+ }
+
+ set named(value) {
+ setOptionalAttribute(this, 'named', value);
+ }
+
+ get describedAs() {
+ return this.getAttribute('described-as') || '';
+ }
+
+ set describedAs(value) {
+ setOptionalAttribute(this, 'described-as', value);
+ }
+
+ get descriptionAs() {
+ return normalizeDescriptionPresentation(this.getAttribute('description-as'));
+ }
+
+ set descriptionAs(value) {
+ setOptionalAttribute(this, 'description-as', value);
+ }
+
+ get resizableColumns() {
+ return this.hasAttribute('resizable-columns');
+ }
+
+ set resizableColumns(value) {
+ setBooleanAttribute(this, 'resizable-columns', value);
+ }
+
+ get reorderableColumns() {
+ return this.hasAttribute('reorderable-columns');
+ }
+
+ set reorderableColumns(value) {
+ setBooleanAttribute(this, 'reorderable-columns', value);
+ }
+
+ get columns() {
+ return Object.freeze(this._columns.map(column => Object.freeze({...column})));
+ }
+
+ set columns(value) {
+ this._columns = normalizeColumns(value);
+ this.gridHostRevision += 1;
+ this.render();
+ }
+
+ get result() {
+ return this._result;
+ }
+
+ set result(value) {
+ this.resultGeneration += 1;
+ this.gridHostRevision += 1;
+ if (value == null) {
+ this._result = null;
+ this.resultState = frozenState('idle');
+ } else if (value?.kind !== 'collection' || !Array.isArray(value.value)) {
+ this._result = null;
+ this.resultState = frozenState('unsupported', [], [{message: 'A normalized collection action result is required.'}]);
+ } else {
+ const rows = Object.freeze([...value.value]);
+ this._result = Object.freeze({kind: 'collection', value: rows});
+ this.resultState = frozenState(rows.length === 0 ? 'empty' : 'ready', rows);
+ }
+ this.render();
+ this.#publishState();
+ }
+
+ get rendererRegistry() {
+ return this._rendererRegistry;
+ }
+
+ set rendererRegistry(value) {
+ this._rendererRegistry = value ?? defaultValueRendererRegistry;
+ this.gridHostRevision += 1;
+ this.render();
+ }
+
+ get gridQualification() {
+ return this._gridQualification;
+ }
+
+ get gridProjection() {
+ return this._gridProjection;
+ }
+
+ connectedCallback() {
+ this.connectionStarted = true;
+ this.classList?.add?.('causeway-standalone-collection-host');
+ globalThis.document?.addEventListener?.(CAUSEWAY_GRID_WIDGET_POLICY_EVENT, this.gridPolicyListener);
+ this.columnObserver?.observe(this, {childList: true});
+ captureDeclarativeStandaloneCollectionColumns(this);
+ this.#captureColumns();
+ this.gridResizeObserver?.observe(this);
+ this.render();
+ this.#publishState();
+ }
+
+ disconnectedCallback() {
+ this.connectionStarted = false;
+ this.resultGeneration += 1;
+ this.gridHostRevision += 1;
+ this.gridResizeRevision += 1;
+ globalThis.document?.removeEventListener?.(CAUSEWAY_GRID_WIDGET_POLICY_EVENT, this.gridPolicyListener);
+ this.columnObserver?.disconnect();
+ this.gridResizeObserver?.disconnect();
+ }
+
+ attributeChangedCallback(name, oldValue, newValue) {
+ if (oldValue === newValue || !this.connectionStarted) return;
+ if (name === 'resizable-columns' || name === 'reorderable-columns') this.gridHostRevision += 1;
+ this.render();
+ }
+
+ acceptGridResponsiveState(wide) {
+ const next = wide === true;
+ if (next === this._gridWide) return false;
+ this._gridWide = next;
+ this.gridResponsiveRevision += 1;
+ this.gridHostRevision += 1;
+ this.render();
+ return true;
+ }
+
+ async requestResultRange(
+ {offset = 0, size = null} = {},
+ generation = this.resultGeneration,
+ hostRevision = this.gridHostRevision
+ ) {
+ const requestedSize = size ?? Math.max(this._gridProjection.rows.length, 1);
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(requestedSize) || requestedSize < 1) {
+ throw new RangeError('Standalone collection ranges require a non-negative offset and positive size.');
+ }
+ await Promise.resolve();
+ if (!this.isConnected
+ || generation !== this.resultGeneration
+ || hostRevision !== this.gridHostRevision) {
+ const error = new Error('Standalone collection result range was superseded.');
+ error.name = 'AbortError';
+ throw error;
+ }
+ return Object.freeze({rows: Object.freeze(this._gridProjection.rows.slice(offset, offset + requestedSize))});
+ }
+
+ render() {
+ const primary = this.#primary();
+ if (!primary) return;
+ try {
+ const label = this.named.trim() || 'Action result';
+ const description = normalizedText(this.describedAs) === normalizedText(label) ? '' : this.describedAs.trim();
+ const descriptionVisible = this.descriptionAs === DescriptionPresentation.LABEL;
+ const tooltip = description && !descriptionVisible ? description : '';
+ const describedBy = description ? this.descriptionId : '';
+ this.#qualifyGrid();
+ let content;
+ if (this.resultState.status === 'idle') {
+ content = '<span class="causeway-empty" role="status">No result</span>';
+ } else if (this.resultState.status === 'unsupported') {
+ content = `<span class="causeway-unsupported" role="alert">${escapeHtml(this.resultState.errors[0]?.message ?? 'Unsupported action result.')}</span>`;
+ } else if (this.resultState.rows.length === 0) {
+ content = '<span class="causeway-empty" role="status">No items</span>';
+ } else {
+ content = this._gridQualification.qualified
+ ? `<${CAUSEWAY_COLLECTION_GRID} data-causeway-collection-grid></${CAUSEWAY_COLLECTION_GRID}>`
+ : this._columns.length > 0
+ ? this.#renderTable(this.resultState.rows)
+ : this.#renderRows(this.resultState.rows);
+ }
+ const count = ['ready', 'empty'].includes(this.resultState.status)
+ ? `<output class="causeway-standalone-collection-count">${this.resultState.totalCount} result${this.resultState.totalCount === 1 ? '' : 's'}</output>`
+ : '';
+ primary.innerHTML = `<section class="causeway-collection causeway-standalone-collection" aria-labelledby="${this.labelId}"${describedBy ? ` aria-describedby="${describedBy}"` : ''}>
+ <h2 id="${this.labelId}" class="causeway-collection-label${tooltip ? ' causeway-member-tooltip' : ''}"${tooltip ? ` tabindex="0" data-tooltip="${escapeHtml(tooltip)}" aria-describedby="${this.descriptionId}"` : ''}>${escapeHtml(label)}</h2>
+ ${description ? `<p id="${this.descriptionId}" class="causeway-collection-description${descriptionVisible ? '' : ' causeway-visually-hidden'}">${escapeHtml(description)}</p>` : ''}
+ ${count}
+ <div class="causeway-collection-content">${content}</div>
+</section>`;
+ if (this._gridQualification.qualified) this.#installGrid(describedBy);
+ } catch (error) {
+ this.resultState = frozenState('error', [], [{message: error?.message ?? String(error)}]);
+ this._gridProjection = buildCausewayGridProjection();
+ this._gridQualification = qualifyCausewayCollectionGrid();
+ publishCausewayGridDiagnostics(this, this._gridQualification);
+ primary.innerHTML = `<section class="causeway-collection causeway-standalone-collection" aria-labelledby="${this.labelId}">
+ <h2 id="${this.labelId}" class="causeway-collection-label">${escapeHtml(this.named.trim() || 'Action result')}</h2>
+ <div class="causeway-collection-content"><span class="causeway-error" role="alert">${escapeHtml(error?.message ?? String(error))}</span></div>
+</section>`;
+ }
+ }
+
+ #renderRows(rows) {
+ return `<ul class="causeway-collection-rows">${rows.map(row => {
+ const metadata = row?._meta;
+ if (validIdentity(metadata)) return `<li>${objectLink(metadata)}</li>`;
+ const rendered = renderCausewayValue({value: row, descriptor: null}, this._rendererRegistry);
+ return `<li>${rendered.html}</li>`;
+ }).join('')}</ul>`;
+ }
+
+ #renderTable(rows) {
+ const header = `<th scope="col">Item</th>${this._columns.map(column => `<th scope="col"${column.testId ? ` data-testid="${escapeHtml(column.testId)}"` : ''}>${escapeHtml(column.label || humanize(column.member))}</th>`).join('')}`;
+ const body = rows.map((row, rowIndex) => {
+ const metadata = row?._meta;
+ const key = rowKey(row, rowIndex);
+ const item = `<td data-causeway-grid-row-key="${escapeHtml(key)}" data-causeway-grid-member="_meta" data-causeway-grid-role="object-link">${validIdentity(metadata) ? objectLink(metadata) : '<span class="causeway-unavailable">Unavailable</span>'}</td>`;
+ const cells = this._columns.map(column => this.#renderCell(row, rowIndex, column, key)).join('');
+ return `<tr data-row-index="${rowIndex}" data-causeway-grid-row-key="${escapeHtml(key)}">${item}${cells}</tr>`;
+ }).join('');
+ return `<table class="causeway-collection-table"><thead><tr>${header}</tr></thead><tbody>${body}</tbody></table>`;
+ }
+
+ #renderCell(row, rowIndex, column, key) {
+ const identity = ` data-causeway-grid-row-key="${escapeHtml(key)}" data-causeway-grid-member="${escapeHtml(column.member)}" data-causeway-grid-role="cell"`;
+ if (!row || !Object.prototype.hasOwnProperty.call(row, column.member)) {
+ return `<td${identity}><span class="causeway-unavailable">Unavailable</span></td>`;
+ }
+ const property = row[column.member];
+ const error = property?.errors?.[0]?.message ?? property?.error?.message ?? null;
+ if (error) return `<td${identity} class="causeway-error" role="alert">${escapeHtml(error)}</td>`;
+ if (property?.hidden === true) return `<td${identity} hidden></td>`;
+ const disabledReason = typeof property?.disabled === 'string' ? property.disabled : '';
+ const value = property && typeof property === 'object' && Object.prototype.hasOwnProperty.call(property, 'get')
+ ? property.get
+ : property;
+ const rendered = renderCausewayValue({value, descriptor: null}, this._rendererRegistry);
+ return `<td${identity}${disabledReason ? ` aria-disabled="true" title="${escapeHtml(disabledReason)}"` : ''}>${rendered.html}</td>`;
+ }
+
+ #qualifyGrid() {
+ const rows = this.resultState.rows;
+ const policy = causewayGridWidgetConfiguration();
+ this._gridProjection = buildCausewayGridProjection({
+ rows,
+ columns: this._columns,
+ rendererRegistry: this._rendererRegistry
+ });
+ const columnsSupported = this._columns.every(column => rows.every(row => row
+ && Object.prototype.hasOwnProperty.call(row, column.member)));
+ const window = finiteWindow(rows.length);
+ this._gridQualification = qualifyCausewayCollectionGrid({
+ active: true,
+ visible: true,
+ wide: this._gridWide,
+ ready: this.resultState.status === 'ready',
+ policyEnabled: policy.enabled,
+ familyHealthy: !policy.failed,
+ connected: this.isConnected,
+ columnsSupported,
+ hasVisibleColumn: this._gridProjection.columns.length > 0 && rows.every(row => validIdentity(row?._meta)),
+ renderersSupported: this._gridProjection.supported,
+ bounded: false,
+ orderingBasis: 'CONFIGURED',
+ rows,
+ window,
+ lifecycle: {
+ hostRevision: this.gridHostRevision,
+ responsiveRevision: this.gridResponsiveRevision,
+ policyRevision: policy.revision,
+ rendererRevision: this.gridHostRevision
+ }
+ });
+ publishCausewayGridDiagnostics(this, this._gridQualification);
+ }
+
+ #installGrid(describedBy) {
+ const adapter = this.#primary()?.querySelector?.(`${CAUSEWAY_COLLECTION_GRID}[data-causeway-collection-grid]`);
+ if (!adapter || !this.isConnected) return;
+ const generation = this.resultGeneration;
+ const hostRevision = this.gridHostRevision;
+ const totalCount = this._gridProjection.rows.length;
+ adapter.presentation = {
+ mode: 'virtual',
+ rows: this._gridProjection.rows,
+ columns: this._gridProjection.columns,
+ totalCount,
+ pageSize: Math.max(totalCount, 1),
+ labelledBy: this.labelId,
+ describedBy,
+ testId: this.getAttribute('data-testid') ? `${this.getAttribute('data-testid')}-grid` : '',
+ resizableColumns: this.resizableColumns,
+ reorderableColumns: this.reorderableColumns,
+ sortableMembers: [],
+ sortCriterion: null,
+ rangeProvider: request => this.requestResultRange(request, generation, hostRevision)
+ };
+ }
+
+ #primary() {
+ let primary = [...(this.children ?? [])].find(child => child.hasAttribute?.('data-causeway-standalone-primary'));
+ if (!primary && globalThis.document?.createElement) {
+ primary = document.createElement('div');
+ primary.setAttribute('data-causeway-standalone-primary', '');
+ this.appendChild(primary);
+ }
+ return primary ?? null;
+ }
+
+ #acceptColumn(column) {
+ if (!column?.member) return;
+ const frozen = Object.freeze({...column});
+ const existing = this._columns.findIndex(candidate => candidate.member === frozen.member);
+ if (existing >= 0 && sameColumn(this._columns[existing], frozen)) return;
+ if (existing >= 0) this._columns.splice(existing, 1, frozen);
+ else this._columns.push(frozen);
+ this.gridHostRevision += 1;
+ this.render();
+ }
+
+ #captureColumns({replace = false} = {}) {
+ const captured = initialColumnConfigurations.get(this) ?? declarativeColumns(this);
+ initialColumnConfigurations.delete(this);
+ if (replace) this._columns = [];
+ for (const column of captured) {
+ if (!this._columns.some(candidate => candidate.member === column.member)) {
+ this._columns.push(Object.freeze({...column}));
+ }
+ }
+ }
+
+ #publishState() {
+ this.dispatchEvent(createSemanticEvent(CausewaySemanticEvent.COLLECTION_STATE, Object.freeze({
+ element: this,
+ member: null,
+ standalone: true,
+ generation: this.resultGeneration,
+ state: this.resultState
+ })));
+ }
+}
+
+function declarativeColumns(collection) {
+ return [...(collection.children ?? collection.childNodes ?? [])]
+ .filter(child => child?.localName === 'cw-collection-column' || child?.configuration?.member)
+ .map(child => ({
+ member: child.configuration?.member ?? child.id ?? '',
+ label: child.configuration?.label ?? child.getAttribute?.('label') ?? '',
+ testId: child.configuration?.testId ?? child.getAttribute?.('data-testid') ?? null
+ }))
+ .filter(column => column.member);
+}
+
+function normalizeColumns(value) {
+ return [...(value ?? [])]
+ .map(column => typeof column === 'string' ? {member: column, label: humanize(column)} : {...column})
+ .filter(column => column.member)
+ .map(column => Object.freeze(column));
+}
+
+function sameColumn(left, right) {
+ return left.member === right.member && left.label === right.label && left.testId === right.testId;
+}
+
+function frozenState(status, rows = [], errors = []) {
+ return Object.freeze({
+ status,
+ rows: Object.freeze([...rows]),
+ totalCount: rows.length,
+ errors: Object.freeze(errors.map(error => Object.freeze({message: String(error?.message ?? error)})))
+ });
+}
+
+function finiteWindow(count) {
+ const size = Math.max(count, 1);
+ return Object.freeze({
+ offset: 0,
+ requestedSize: size,
+ maximumSize: size,
+ returnedCount: count,
+ totalCount: count,
+ hasPrevious: false,
+ hasNext: false,
+ ordering: 'CONFIGURED'
+ });
+}
+
+function validIdentity(metadata) {
+ return Boolean(metadata?.logicalTypeName && metadata?.id);
+}
+
+function objectLink(metadata) {
+ return `<cw-object-link logical-type="${escapeHtml(metadata.logicalTypeName)}" object-id="${escapeHtml(metadata.id)}" title="${escapeHtml(metadata.title ?? metadata.id)}"${metadata.icon ? ` icon="${escapeHtml(metadata.icon)}"` : ''}></cw-object-link>`;
+}
+
+function rowKey(row, index) {
+ const metadata = row?._meta;
+ return validIdentity(metadata) ? `${metadata.logicalTypeName}:${metadata.id}` : `result:${index}`;
+}
+
+function humanize(value) {
+ return String(value || '').replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/^./, character => character.toUpperCase());
+}
+
+function normalizedText(value) {
+ return String(value ?? '').trim().toLocaleLowerCase();
+}
+
+function setOptionalAttribute(element, name, value) {
+ if (value == null || value === '') element.removeAttribute(name);
+ else element.setAttribute(name, String(value));
+}
+
+function setBooleanAttribute(element, name, value) {
+ if (value === true) element.setAttribute(name, '');
+ else element.removeAttribute(name);
+}
+
+function collectionBreakpointPixels() {
+ const candidate = globalThis.getComputedStyle?.(globalThis.document?.documentElement)?.fontSize;
+ const rootFontSize = Number.parseFloat(candidate);
+ return 48 * (Number.isFinite(rootFontSize) && rootFontSize > 0 ? rootFontSize : 16);
+}
diff --git a/viewers/webcomponents/foundation/src/theme.css b/viewers/webcomponents/foundation/src/theme.css
index 3bcfc502784..6c51439fe77 100644
--- a/viewers/webcomponents/foundation/src/theme.css
+++ b/viewers/webcomponents/foundation/src/theme.css
@@ -236,6 +236,7 @@ cw-object-context,
cw-object-header,
cw-property,
cw-collection,
+cw-standalone-collection,
cw-interaction-controller {
min-width: 0;
display: block;
@@ -570,6 +571,11 @@ cw-collection[data-causeway-collection-heading-actions] > .causeway-member-prima
box-shadow: none;
}
+.causeway-standalone-collection-count {
+ color: var(--causeway-muted);
+ font-size: var(--causeway-font-size-sm);
+}
+
.causeway-collection-content {
min-width: 0;
overflow-x: auto;
diff --git a/viewers/webcomponents/foundation/test/domain-components.test.mjs b/viewers/webcomponents/foundation/test/domain-components.test.mjs
index 8bde84df1d6..7ac4e3fa9a0 100644
--- a/viewers/webcomponents/foundation/test/domain-components.test.mjs
+++ b/viewers/webcomponents/foundation/test/domain-components.test.mjs
@@ -63,6 +63,7 @@ test('registers the complete compact custom-element vocabulary without old alias
'cw-interaction-controller',
'cw-reference-editor',
'cw-collection',
+ 'cw-standalone-collection',
'cw-collection-column',
'cw-menubars',
'cw-menubar-primary',
diff --git a/viewers/webcomponents/foundation/test/element-prefix.test.mjs b/viewers/webcomponents/foundation/test/element-prefix.test.mjs
index c5c4e1c3f33..8e708c338ae 100644
--- a/viewers/webcomponents/foundation/test/element-prefix.test.mjs
+++ b/viewers/webcomponents/foundation/test/element-prefix.test.mjs
@@ -58,6 +58,7 @@ const OLD_SUFFIXES = [
'field-editor',
'reference-editor',
'collection',
+ 'standalone-collection',
'collection-column',
'menubars',
'menubar-primary',
@@ -159,10 +160,11 @@ test('application markup does not expose raw Vaadin elements', async () => {
});
test('compact element names retain established non-element Causeway contracts', () => {
- assert.equal(Object.values(CausewayElementName).length, 18);
+ assert.equal(Object.values(CausewayElementName).length, 19);
assert.ok(Object.values(CausewayElementName).every(name => name.startsWith('cw-')));
assert.equal(CAUSEWAY_FIELD_EDITOR, 'cw-field-editor');
assert.equal(CausewayHostClass.PROPERTY, 'causeway-property');
assert.equal(CausewayHostClass.PARAMETER, 'causeway-parameter');
+ assert.equal(CausewayHostClass.STANDALONE_COLLECTION, 'causeway-standalone-collection');
assert.equal(CausewaySemanticEvent.PROPERTY_UPDATED, 'causeway-property-updated');
});
diff --git a/viewers/webcomponents/foundation/test/standalone-collection.test.mjs b/viewers/webcomponents/foundation/test/standalone-collection.test.mjs
new file mode 100644
index 00000000000..44f7b764f01
--- /dev/null
+++ b/viewers/webcomponents/foundation/test/standalone-collection.test.mjs
@@ -0,0 +1,208 @@
+/*
+ * 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.
+ */
+
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {installDomShim} from './dom-shim.mjs';
+
+const {document} = installDomShim();
+const {
+ COLLECTION_STATE_EVENT,
+ captureDeclarativeStandaloneCollectionColumns,
+ CausewayCollectionColumnElement,
+ CausewayStandaloneCollectionElement,
+ configureCausewayGridWidgets,
+ defineCausewayWebComponents
+} = await import('../src/index.mjs');
+
+defineCausewayWebComponents();
+
+function object(id, title = id, extra = {}) {
+ return {
+ _meta: {
+ logicalTypeName: 'example.Result',
+ id,
+ title,
+ icon: `/graphql/object/example.Result:${id}/_meta/icon`
+ },
+ ...extra
+ };
+}
+
+test('standalone collection captures declarations before browser upgrade replaces source children', () => {
+ const collection = new CausewayStandaloneCollectionElement();
+ const column = new CausewayCollectionColumnElement();
+ column.id = 'name';
+ column.label = 'Name';
+ column.setAttribute('data-testid', 'column-name');
+ collection.appendChild(column);
+ captureDeclarativeStandaloneCollectionColumns({querySelectorAll: () => [collection]});
+ collection.removeChild(column);
+ document.body.appendChild(collection);
+
+ assert.deepEqual(collection.columns, [{member: 'name', label: 'Name', testId: 'column-name'}]);
+ document.body.removeChild(collection);
+});
+
+test('standalone collection snapshots normalized results and publishes bounded lifecycle state', () => {
+ const collection = new CausewayStandaloneCollectionElement();
+ collection.named = 'Matching owners';
+ collection.describedAs = 'Owners returned by the action';
+ collection.descriptionAs = 'tooltip';
+ document.body.appendChild(collection);
+ const states = [];
+ collection.addEventListener(COLLECTION_STATE_EVENT, event => states.push(event.detail));
+
+ const source = [object('1', 'Ada <Lovelace>')];
+ collection.result = {kind: 'collection', value: source};
+ source.push(object('2'));
+
+ assert.equal(collection.result.value.length, 1);
+ assert.equal(collection.resultState.status, 'ready');
+ assert.equal(collection.resultState.totalCount, 1);
+ assert.equal(collection.hasAttribute('result'), false);
+ assert.match(collection.innerHTML, /Matching owners/);
+ assert.match(collection.innerHTML, /Owners returned by the action/);
+ assert.match(collection.innerHTML, /class="causeway-collection-description causeway-visually-hidden"/);
+ assert.match(collection.innerHTML, /logical-type="example.Result"/);
+ assert.match(collection.innerHTML, /title="Ada <Lovelace>"/);
+ assert.match(collection.innerHTML, /icon="\/graphql\/object\/example.Result:1\/_meta\/icon"/);
+ assert.equal(states.length, 1);
+ assert.equal(states[0].standalone, true);
+ assert.equal(states[0].member, null);
+ assert.equal(states[0].state.status, 'ready');
+
+ collection.result = {kind: 'collection', value: []};
+ assert.equal(collection.resultState.status, 'empty');
+ assert.match(collection.innerHTML, /No items/);
+ assert.doesNotMatch(collection.innerHTML, /causeway-collection-pager/);
+
+ collection.result = null;
+ assert.equal(collection.resultState.status, 'idle');
+ assert.match(collection.innerHTML, /No result/);
+
+ collection.result = {kind: 'scalar', value: 'wrong'};
+ assert.equal(collection.result, null);
+ assert.equal(collection.resultState.status, 'unsupported');
+ assert.match(collection.innerHTML, /normalized collection action result is required/);
+ assert.equal(states.at(-1).state.status, 'unsupported');
+});
+
+test('standalone collection preserves direct child columns and renders only supplied values', () => {
+ const collection = new CausewayStandaloneCollectionElement();
+ const name = document.createElement('cw-collection-column');
+ name.id = 'name';
+ name.label = 'Owner name';
+ name.setAttribute('data-testid', 'owner-name-column');
+ const hidden = document.createElement('cw-collection-column');
+ hidden.id = 'secret';
+ const disabled = document.createElement('cw-collection-column');
+ disabled.id = 'code';
+ const missing = document.createElement('cw-collection-column');
+ missing.id = 'missing';
+ collection.appendChild(name);
+ collection.appendChild(hidden);
+ collection.appendChild(disabled);
+ collection.appendChild(missing);
+ document.body.appendChild(collection);
+
+ collection.result = {kind: 'collection', value: [object('1', 'Ada', {
+ name: {get: 'Ada Lovelace'},
+ secret: {hidden: true, get: 'classified'},
+ code: {get: null, disabled: 'Read only'}
+ })]};
+
+ assert.equal(collection.columns.length, 4);
+ assert.equal(collection.children.includes(name), true);
+ assert.equal(name.parentNode, collection);
+ assert.match(collection.innerHTML, /Owner name/);
+ assert.match(collection.innerHTML, /data-testid="owner-name-column"/);
+ assert.match(collection.innerHTML, /Ada Lovelace/);
+ assert.match(collection.innerHTML, /data-causeway-grid-member="secret"[^>]* hidden/);
+ assert.match(collection.innerHTML, /aria-disabled="true" title="Read only"/);
+ assert.match(collection.innerHTML, /data-causeway-grid-member="missing"[\s\S]*?causeway-unavailable">Unavailable/);
+
+ collection.removeChild(missing);
+ assert.equal(collection.columns.some(column => column.member === 'missing'), false);
+ assert.equal(collection.children.includes(name), true);
+});
+
+test('standalone collection contains renderer failures as local error state', () => {
+ const collection = new CausewayStandaloneCollectionElement();
+ collection.rendererRegistry = {render() { throw new Error('Renderer failed safely.'); }};
+ document.body.appendChild(collection);
+ collection.result = {kind: 'collection', value: ['value']};
+
+ assert.equal(collection.resultState.status, 'error');
+ assert.match(collection.innerHTML, /causeway-error/);
+ assert.match(collection.innerHTML, /Renderer failed safely/);
+});
+
+test('standalone collection renders supported scalar rows without inventing identity', () => {
+ const collection = new CausewayStandaloneCollectionElement();
+ document.body.appendChild(collection);
+ collection.result = {kind: 'collection', value: ['alpha', 42, true, null]};
+
+ assert.match(collection.innerHTML, /alpha/);
+ assert.match(collection.innerHTML, /42/);
+ assert.match(collection.innerHTML, /true/i);
+ assert.match(collection.innerHTML, /causeway-value-null/);
+ assert.doesNotMatch(collection.innerHTML, /cw-object-link/);
+ assert.equal(collection.gridQualification.qualified, false);
+});
+
+test('standalone collection qualifies finite object snapshots and rejects superseded ranges', async () => {
+ configureCausewayGridWidgets({enabled: true});
+ const collection = new CausewayStandaloneCollectionElement();
+ collection.resizableColumns = true;
+ collection.reorderableColumns = true;
+ document.body.appendChild(collection);
+ collection.result = {kind: 'collection', value: [object('1'), object('2')]};
+ collection.acceptGridResponsiveState(true);
+
+ assert.equal(collection.gridQualification.qualified, true);
+ assert.equal(collection.gridQualification.presentation, 'grid-virtual');
+ assert.equal(collection.resizableColumns, true);
+ assert.equal(collection.reorderableColumns, true);
+ assert.equal(collection.gridProjection.rows.length, 2);
+ assert.equal(collection.dataset.causewayGridCount, 'available');
+ const current = await collection.requestResultRange({offset: 1, size: 1});
+ assert.equal(current.rows.length, 1);
+ assert.equal(current.rows[0].key, 'example.Result:2');
+
+ const obsolete = collection.requestResultRange({offset: 0, size: 1});
+ collection.result = {kind: 'collection', value: [object('3')]};
+ await assert.rejects(obsolete, error => error.name === 'AbortError');
+ assert.equal(collection.gridProjection.rows[0].key, 'example.Result:3');
+
+ document.body.removeChild(collection);
+ await assert.rejects(
+ collection.requestResultRange({offset: 0, size: 1}),
+ error => error.name === 'AbortError'
+ );
+ configureCausewayGridWidgets({enabled: true});
+});
+
+test('standalone collection keeps member-only attributes inert and supports native Grid policy', () => {
+ configureCausewayGridWidgets({enabled: false});
+ const collection = new CausewayStandaloneCollectionElement();
+ collection.setAttribute('id', 'not-a-member');
+ collection.setAttribute('active', '');
+ collection.setAttribute('paged', '5');
+ collection.setAttribute('sortable', '');
+ collection.setAttribute('filterable', '');
+ document.body.appendChild(collection);
+ collection.result = {kind: 'collection', value: [object('1')]};
+ collection.acceptGridResponsiveState(true);
+
+ assert.equal(collection.gridQualification.qualified, false);
+ assert.equal(collection.gridQualification.reason, 'policy-native');
+ assert.match(collection.innerHTML, /causeway-collection-rows/);
+ assert.doesNotMatch(collection.innerHTML, /data-causeway-activate|causeway-collection-pager|causeway-collection-search|causeway-collection-sort/);
+ configureCausewayGridWidgets({enabled: true});
+});
diff --git a/viewers/webcomponents/htmx/src/main/resources/META-INF/resources/causeway-htmx/causeway-htmx.css b/viewers/webcomponents/htmx/src/main/resources/META-INF/resources/causeway-htmx/causeway-htmx.css
index db43fbf1aa0..84313fdf8dc 100644
--- a/viewers/webcomponents/htmx/src/main/resources/META-INF/resources/causeway-htmx/causeway-htmx.css
+++ b/viewers/webcomponents/htmx/src/main/resources/META-INF/resources/causeway-htmx/causeway-htmx.css
@@ -188,10 +188,6 @@
font-size: var(--causeway-font-size-lg);
}
-.causeway-result-list {
- margin-block-end: 0;
-}
-
.causeway-shell-main {
min-width: 0;
padding-block: var(--causeway-space-5) var(--causeway-space-8);
diff --git a/viewers/webcomponents/htmx/src/main/resources/META-INF/resources/causeway-htmx/causeway-htmx.mjs b/viewers/webcomponents/htmx/src/main/resources/META-INF/resources/causeway-htmx/causeway-htmx.mjs
index e4cc35551d7..7c0787dcaab 100644
--- a/viewers/webcomponents/htmx/src/main/resources/META-INF/resources/causeway-htmx/causeway-htmx.mjs
+++ b/viewers/webcomponents/htmx/src/main/resources/META-INF/resources/causeway-htmx/causeway-htmx.mjs
@@ -247,24 +247,13 @@ function presentResult(detail) {
const output = document.createElement('output');
const result = detail?.result;
if (result?.kind === 'collection') {
- output.textContent = `${Array.isArray(result.value) ? result.value.length : 0} results`;
- const list = document.createElement('ul');
- list.className = 'causeway-result-list';
- for (const item of result.value ?? []) {
- const metadata = item?._meta;
- const entry = document.createElement('li');
- if (metadata?.logicalTypeName && metadata?.id) {
- const link = document.createElement('a');
- link.href = canonicalObjectPath(basePath, metadata);
- link.dataset.causewayRouteLink = '';
- link.textContent = metadata.title ?? metadata.id;
- entry.append(link);
- } else {
- entry.textContent = 'Result item';
- }
- list.append(entry);
- }
- resultRegion.append(heading, output, list);
+ const count = Array.isArray(result.value) ? result.value.length : 0;
+ const collection = document.createElement('cw-standalone-collection');
+ collection.named = heading.textContent;
+ collection.setAttribute('data-testid', 'causeway-standalone-action-result');
+ resultRegion.append(collection);
+ collection.result = result;
+ output.textContent = `${count} result${count === 1 ? '' : 's'}`;
} else if (result?.kind === 'scalar') {
output.textContent = result.value == null ? '' : String(result.value);
resultRegion.append(heading, output);
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 792eba1c8fe..f89b410d49c 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
@@ -505,6 +505,7 @@ void serviceActionsCoverValidationCancellationScalarAndCollections() {
activateServiceAction("listAll");
waitForShellResult("listAll", "4 results");
+ assertStandaloneCollectionResult("listAll", 4);
assertMenuClosedAndFocused("Pet Owners");
openMenu("Pet Owners");
@@ -517,8 +518,12 @@ void serviceActionsCoverValidationCancellationScalarAndCollections() {
assertFocused(parameter("name"));
fillParameter("name", "Mary");
submitPrompt();
- waitForShellResult("findByName", "1 results");
+ waitForShellResult("findByName", "1 result");
+ assertStandaloneCollectionResult("findByName", 1);
assertMenuClosedAndFocused("Pet Owners");
+ page.locator("cw-standalone-collection cw-object-link[title='Mary Smith (Mary)'] button").click();
+ waitForRoute("petclinic.PetOwner", "s_owner-mary");
+ assertThat(page.locator("[data-testid='causeway-shell-result'] cw-standalone-collection").count()).isZero();
openMenu("Pet Owners");
activateServiceAction("findByNameLike");
@@ -531,7 +536,8 @@ void serviceActionsCoverValidationCancellationScalarAndCollections() {
waitForPrompt("findByNameLike");
fillParameter("name", "James");
submitPrompt();
- waitForShellResult("findByNameLike", "1 results");
+ waitForShellResult("findByNameLike", "1 result");
+ assertStandaloneCollectionResult("findByNameLike", 1);
assertMenuClosedAndFocused("Pet Owners");
openMenu("Pet Owners");
@@ -1501,18 +1507,29 @@ private void assertNarrowMultilinePropertyLayout(final Locator property) {
@SuppressWarnings("unchecked")
private void assertSingleVaadinMultilineFocus(final Locator editor) {
- editor.evaluate("element => element.inputElement.focus()");
- final var focusStyles = (List<String>) editor.evaluate("""
- element => {
- const host = getComputedStyle(element);
- const field = getComputedStyle(element.shadowRoot.querySelector('[part~="input-field"]'));
- const input = getComputedStyle(element.inputElement);
- const inputBorder = ['Top', 'Right', 'Bottom', 'Left']
- .reduce((total, side) => total + Number.parseFloat(input[`border${side}Width`]), 0);
- return [host.outlineStyle, host.outlineWidth, field.outlineStyle, field.outlineWidth,
- String(inputBorder), input.outlineStyle];
- }
- """);
+ List<String> focusStyles = List.of();
+ for (var attempt = 0; attempt < 10; attempt++) {
+ editor.evaluate("element => element.inputElement.focus()");
+ page.waitForTimeout(50);
+ focusStyles = (List<String>) editor.evaluate("""
+ element => {
+ const host = getComputedStyle(element);
+ const field = getComputedStyle(element.shadowRoot.querySelector('[part~="input-field"]'));
+ const input = getComputedStyle(element.inputElement);
+ const inputBorder = ['Top', 'Right', 'Bottom', 'Left']
+ .reduce((total, side) => total + Number.parseFloat(input[`border${side}Width`]), 0);
+ return [host.outlineStyle, host.outlineWidth, field.outlineStyle, field.outlineWidth,
+ String(inputBorder), input.outlineStyle];
+ }
+ """);
+ if (focusStyles.get(0).equals("none")
+ && focusStyles.get(2).equals("solid")
+ && Double.parseDouble(focusStyles.get(3).replace("px", "")) > 0.0
+ && Double.parseDouble(focusStyles.get(4)) == 0.0
+ && focusStyles.get(5).equals("none")) {
+ break;
+ }
+ }
assertThat(focusStyles.get(0)).isEqualTo("none");
assertThat(focusStyles.get(2)).isEqualTo("solid");
assertThat(Double.parseDouble(focusStyles.get(3).replace("px", ""))).isGreaterThan(0.0);
@@ -1527,6 +1544,26 @@ private void waitForShellResult(final String actionId, final String value) {
java.util.Map.of("action", actionId, "value", value));
}
+ private void assertStandaloneCollectionResult(final String actionId, final int expectedCount) {
+ final var result = page.locator("[data-testid='causeway-shell-result'] cw-standalone-collection");
+ result.waitFor();
+ page.waitForFunction("args => { const element = document.querySelector(\"[data-testid='causeway-shell-result'] cw-standalone-collection\"); return element?.resultState?.status === (args.count === 0 ? 'empty' : 'ready') && element.resultState.totalCount === args.count; }",
+ java.util.Map.of("count", expectedCount));
+ assertThat(result.getAttribute("named")).isEqualTo(actionId + " result");
+ assertThat(((Number) result.evaluate("element => element.resultState.totalCount")).intValue())
+ .isEqualTo(expectedCount);
+ assertThat(page.locator("[data-testid='causeway-shell-result'] > ul").count()).isZero();
+ if (expectedCount > 0) {
+ assertObjectLinkIcon(result.locator("cw-object-link").first());
+ }
+ if (nativeToolkit()) {
+ assertThat(result.locator("cw-collection-grid").count()).isZero();
+ } else if (expectedCount > 0) {
+ page.waitForFunction("() => document.querySelector(\"[data-testid='causeway-shell-result'] cw-standalone-collection\")?.dataset.causewayGridPresentation === 'grid-virtual'");
+ assertThat(result.locator("cw-collection-grid").count()).isEqualTo(1);
+ }
+ }
+
private long graphQLOperationCount(final String operationName) {
return graphQLRequests.stream()
.filter(body -> body != null && body.contains(operationName))