CWA 2 is a prerelease (2.0.0-alpha), heading for a beta. It runs production sites; configuration can still change between releases, always with upgrade notes. View versions and support
Component

useCwaComponent

The recommended entry point for all CWA display components — fetch resource data, expose to the admin manager, and compose plugins for collections, uploaded files, or custom behaviour.

The recommended composable for all CWA display components. Wraps useCwaResource and adds a typed plugin system so collection, file, and custom behaviours can be composed together without nesting.

const props = defineProps<IriProp>()
const { resource, exposeMeta } = useCwaComponent(props)
defineExpose(exposeMeta)

Signature

useCwaComponent(
  props: IriProp,
  plugins?: CwaResourcePlugin[],
  ops?: {
    name?: string
    manager?: {
      disabled?: boolean
    }
  }
)

Parameters

ParameterTypeDescription
propsIriPropThe raw defineProps<IriProp>() result. No toRef needed
pluginsCwaResourcePlugin[]Optional plugin factory results, such as withCollection() and withFile(). See Plugins
opsobjectThe same options as useCwaResource: name and manager.disabled (opt out of the admin manager)

A component's name, styles and admin settings aren't options here. They are declared with defineCwaConfig in the same file; see Component Files › Configuring a Component.

Return Values

const { resource, exposeMeta, $cwa, styleKeys, ...pluginReturns } = useCwaComponent(props)
ReturnTypePurpose
resourceComputedRef<CwaCurrentResourceInterface | undefined>Reactive resource ref — access data on .value?.data
exposeMetaobjectPass directly to defineExpose
$cwaCwaComposableAuth, resources, UI state
styleKeysComputedRef<string[]>The keys of the styles an admin picked, in stored order. See Style Variants
uiClassNamesComputedRef<string[] | undefined>What the resource stores: one style:<key> entry for each picked style
publishedIriComputedRef<string>The published IRI of this component, or its own IRI if it was never published. Never empty. See below
...pluginReturnsmerged objectAll return values from provided plugins

defineExpose(exposeMeta) is required — without it the admin manager cannot select this component.

publishedIri falls back to the component's own IRI because an unpublished draft is still a valid group location. You rarely need it: a nested <CwaComponentGroup> resolves its location to the published IRI itself, so pass it iri.

Example

<template>
  <div v-if="resource?.data">
    <h2>{{ resource.data.title }}</h2>
  </div>
</template>

<script setup lang="ts">
import type { IriProp } from '#cwa/composables/cwa-resource'
import { useCwaComponent } from '#imports'

const props = defineProps<IriProp>()
const { resource, exposeMeta } = useCwaComponent(props)
defineExpose(exposeMeta)
</script>

resource.value states:

  • undefined — the store has no entry for this IRI yet
  • object without data — the fetch is in progress or failed (apiState.status says which)
  • object with data — data available

Plugins

Plugins extend useCwaComponent with additional state and methods. Pass an array of plugin factory results as the second argument. Return values from all plugins are merged and destructured alongside the base returns.

withCollection()

For components backed by the built-in Collection API resource. Returns pagination state and navigation helpers.

import { useCwaComponent, withCollection } from '#imports'

const props = defineProps<IriProp>()
const {
  resource,
  exposeMeta,
  collectionItems,
  isLoadingCollection,
  totalPages,
  pageModel,
  goToNextPage,
  goToPreviousPage,
  changePage,
  resolveResourceLink,
} = useCwaComponent(props, [withCollection()])
defineExpose(exposeMeta)
ReturnTypePurpose
collectionItemsComputedRef<CwaResource[] | undefined>The response's collection.member array. Each item is a raw API resource, so read its fields directly (item.title, not item.data.title). undefined until the first response arrives
isLoadingCollectionRef<boolean>true while a re-fetch after a query change is in progress. The first page comes with the component's own data, so this stays false for it
totalPagesRef<number>Parsed from the page parameter of the collection's view.last link; 1 when there is no last-page link
pageModelRef<number>Current page number, bound to the URL's ?page= parameter. Set it to change page
goToNextPage() => voidMoves to the next page. Does nothing on the last page
goToPreviousPage() => voidMoves to the previous page. Does nothing on page 1
changePage(page: number) => voidJumps to a page. It doesn't check the page exists
resolveResourceLink(resource, property) => string | RouteLocationLink target for a collection item. See Linking to a Resource's Page

The three page-changing functions also scroll the window to the top. The collection re-fetches whenever the URL query changes, and returns to page 1 when anything other than page or perPage changes. Collections & Pagination shows a full component, numbered pagination and user-controlled sorting.

Replaces the deprecated useCwaCollectionResource.

withFile()

withFile(fileOps?) is for components backed by a PHP entity with #[Silverback\Uploadable]. It handles any uploadable file, not just images. Rather than flat return values, it exposes the field under a files map keyed by its fileProp (default 'file') — so files.file.contentUrl, files.file.displayMedia, etc. Map entries are reactive, so in templates you access them without .value.

import { useCwaComponent, withFile } from '#imports'

const props = defineProps<IriProp>()
const { resource, exposeMeta, files } = useCwaComponent(props, [withFile()])
defineExpose(exposeMeta)

// files.file.contentUrl · files.file.displayMedia · files.file.srcset · files.file.handleLoad · files.file.loaded

Options (fileOps):

OptionDescription
filePropName of the PHP #[UploadableField] property holding the file, and the files map key (default: file)
imagineFilterNameImagine filter variant to surface as displayMedia/contentUrl (image-specific)
imageRefOptional template ref for the <img>, to detect an image already loaded from cache. Never registered for you — see useCwaFileField

Each entry in files exposes contentUrl, displayMedia (a MediaFile with width/height/mimeType), srcset (every sized variant, for a responsive <img>; see srcset), handleLoad, and loaded. See Images & Media for the full display pattern, and useCwaFileField for the standalone per-field variant.

If you rely on loaded, pass an imageRef typed useTemplateRef<unknown>(…); see Why imageRef exists.

Multiple File Fields

Use withFile() once per field, each with its own fileProp. useCwaComponent's plugin merge accumulates the files key rather than overwriting it, so the fields never collide:

const { files } = useCwaComponent(props, [
  withFile({ fileProp: 'heroImage' }),
  withFile({ fileProp: 'thumbnail', imagineFilterName: 'small' }),
])
// files.heroImage.contentUrl · files.thumbnail.contentUrl

Combining Plugins

Multiple plugins can be composed in a single call:

const { resource, exposeMeta, collectionItems, files } = useCwaComponent(
  props,
  [withCollection(), withFile()]
)
defineExpose(exposeMeta)

Style Variants

Styles are declared in the component's defineCwaConfig, keyed by a name of your choice:

<script setup lang="ts">
defineCwaConfig({
  styles: {
    filled: { label: 'Filled', classes: 'bg-blue-600 text-white px-6 py-2 rounded-md' },
    outlined: { label: 'Outlined', classes: 'border border-blue-600 text-blue-600 px-6 py-2' },
  },
})

const props = defineProps<IriProp>()
const { resource, exposeMeta, styleKeys } = useCwaComponent(props)
defineExpose(exposeMeta)

const filled = computed(() => styleKeys.value.includes('filled'))
</script>

The label is what the admin's Style select shows, and classes is a class string. The key is what the resource stores, as style:filled in uiClassNames. Pick a key you won't need to rename; the label and the classes can change freely.

The module puts the picked styles' classes on the component's root element, so you don't bind them. It looks the classes up when the page renders, on the server too, so a change to a style's classes reaches every component that uses it on the next deploy. An entry in uiClassNames that isn't a style: key of the rendering file renders nothing.

styleKeys lists every stored key, so use it for logic keyed off the picked style, such as an extra element.

Allowing Several Styles at Once

Set allowMultiple: true in defineCwaConfig to let an admin pick more than one style. The Style select becomes a multi-select, and the classes of every picked style are combined on the element:

defineCwaConfig({
  allowMultiple: true,
  styles: {
    bordered: { label: 'Bordered', classes: 'border border-gray-200' },
    rounded: { label: 'Rounded', classes: 'rounded' },
  },
})

Picking both saves uiClassNames: ['style:bordered', 'style:rounded']. A single pick is a one-element array.

Styles and UI Variants

A UI variant in ui/ can declare its own styles. Then the admin offers only those while the variant is picked. A variant that declares no styles offers the primary component's, and takes its allowMultiple too. Switching a component to another UI keeps only the stored keys the new one defines.

Styling an Inner Element

The classes always go on the root element. To style an inner element by the picked style, test styleKeys:

<template>
  <div>
    <a :class="{ 'underline': styleKeys.includes('underlined') }">{{ resource?.data?.label }}</a>
  </div>
</template>

Writing a Custom Plugin

A plugin is a function that receives { iri, resource, $cwa } and returns any object:

import type { CwaResourcePlugin } from '#cwa/composables/cwa-component'

const withWordCount = (): CwaResourcePlugin<{ wordCount: ComputedRef<number> }> => {
  return ({ resource }) => {
    const wordCount = computed(() => {
      const body = resource.value?.data?.body ?? ''
      return body.split(/\s+/).filter(Boolean).length
    })
    return { wordCount }
  }
}

// Usage
const { resource, exposeMeta, wordCount } = useCwaComponent(props, [withWordCount()])