LSP and MCP support for Custom Elements - intelligent autocomplete, validation, and AI-native component understanding

version
0.11.8
GitHub stars
47

Install

/plugin install cem@cem-plugins

Run it inside Claude Code after adding the marketplace with /plugin marketplace add bennypowers/cem.

Contents

Discovered from source

Skills 12

Accessibility Review

Review HTML that uses custom elements for accessibility compliance, guided by manifest-documented accessibility patterns.

Workflow

Phase 1: Gather Context

  1. Read the accessibility resource for the project's manifest-documented a11y patterns:
cem://accessibility
  1. Identify the target HTML to review. Either:

    • The user provides an HTML snippet directly
    • The user points to a file — read it with the Read tool
    • Search for HTML files with custom elements using Glob/Grep
  2. For each custom element found in the HTML, read its element resource:

cem://element/{tagName}

And its slot guidelines:

cem://element/{tagName}/slots

Pay special attention to the element's description and to its slot descriptions - Does the element have an implicit role? Do slots require a specific role to be slotted into them?

Phase 2: Validate with MCP Tool

Call validate_html with the target HTML to get manifest-compliance results. This catches:

  • Unknown attributes and typos
  • Invalid enum values
  • Slot content guideline violations
  • Attribute conflicts (e.g. disabled + interactive)

Phase 3: Manifest-Driven Accessibility Analysis

Cross-reference the HTML against manifest data. Check for:

Slot Content Accessibility
  • Read each slot's description carefully for content requirements ("must contain", "must not contain", "expects", "requires")
  • Check if slot descriptions specify a required role (e.g. "expects an element with role listitem")
  • Do slotted elements preserve heading hierarchy?
  • Are interactive elements placed in slots that expect them?
  • Is text content provided for slots that need accessible labels?
Attribute Accessibility
  • Are ARIA-related attributes used correctly per the manifest?
  • Are required attributes present (especially those with accessibility implications)?
  • Do boolean attributes like disabled have matching ARIA state considerations?
Element Composition
  • Are elements nested in ways that maintain accessibility?
  • Are label/description associations correct?
  • Are focusable elements reachable and in logical tab order?
Content Patterns
  • Do elements that act as landmarks have appropriate labels?
  • Are images/icons inside custom elements accompanied by text alternatives?
  • Are live regions used appropriately?
Element Roles
  • Check the element's description for implicit role information (e.g. "acts as a button", "has role navigation", "implicit role listbox")
  • If the element description states an implicit role, do not recommend adding an explicit role attribute

Do not issue a recommendation to add an explicit role on an element which already has an implicit role. Do not recommend to use aria-label or other aria attributes on elements which provide custom attributes which handle the same things; i.e. check element's attributes for descriptions like "The accessible-label attribute sets the screen reader's content for this element" or "The audible-content attribute sets the element's name for assistive technology", etc.

Phase 4: Report

Output a structured report:

## Accessibility Review

### Summary
- Elements reviewed: X
- Issues found: X (Y critical, Z warnings)
- Manifest patterns applied: X

### Critical Issues
[Issues that will cause accessibility failures]

### Warnings
[Issues that may cause problems for some users]

### Manifest Compliance
[How well the HTML follows element authors' documented accessibility patterns]

### Recommendations
[Specific fixes with corrected HTML examples]

Important Principles

  • Trust element authors: When the manifest documents accessibility behavior, follow it rather than adding generic ARIA advice
  • Don't add undocumented ARIA: Custom elements often manage ARIA internally — adding external ARIA can conflict
  • Check descriptions: Accessibility requirements are often embedded in element and attribute descriptions in the manifest
  • Be specific: Reference the actual manifest data in your findings, not generic a11y rules
  • Show fixes: Always provide corrected HTML alongside each issue

Custom Elements in Angular

Generate framework-specific guidance for using custom elements in Angular, including required schema configuration.

Workflow

Phase 1: Detect Angular Version and Style

Search the project for Angular version and patterns:

  • Check package.json for @angular/core version
  • Determine if using standalone components (Angular 14+) or NgModules
  • Check for existing CUSTOM_ELEMENTS_SCHEMA usage
  • Check for TypeScript strict mode settings

Phase 2: Gather Element Data

Read the target element(s):

cem://element/{tagName}
cem://element/{tagName}/attributes
cem://element/{tagName}/events
cem://element/{tagName}/slots

Understand which features need framework-specific handling:

  • Properties: Angular's property binding works well with custom elements
  • Events: Angular's event binding works with custom events
  • Two-way binding: Needs manual setup
  • Forms: Custom elements need ControlValueAccessor for Angular forms

Phase 3: Required Configuration

Standalone Components (Angular 14+, recommended)
// my.component.ts
import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@Component({
  selector: 'app-my-page',
  standalone: true,
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  template: `
    <my-element variant="primary" (my-event)="handleEvent($event)">
      Content
    </my-element>
  `,
})
export class MyPageComponent {
  handleEvent(e: Event) {
    console.log((e as CustomEvent).detail);
  }
}

Each standalone component that uses custom elements needs CUSTOM_ELEMENTS_SCHEMA in its schemas array.

NgModule-based (Angular < 14 or legacy projects)
// app.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@NgModule({
  declarations: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  // ...
})
export class AppModule {}

The schema applies to all components declared in that module. For larger apps, add it only to modules that use custom elements.

Phase 4: Generate Integration Code

Basic Usage
@Component({
  standalone: true,
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  template: `
    <my-element
      variant="primary"
      [disabled]="isDisabled"
      (my-event)="onMyEvent($event)"
    >
      Default slot content
      <span slot="header">Header content</span>
    </my-element>
  `,
})
export class MyComponent {
  isDisabled = false;

  onMyEvent(event: Event) {
    const detail = (event as CustomEvent).detail;
  }
}
Property Binding

Angular's [property] syntax sets properties directly on the element, which works correctly with custom elements:

<!-- Attribute (string) -->
<my-element variant="primary"></my-element>

<!-- Property binding (passes JS values) -->
<my-element [complexData]="myObject"></my-element>

<!-- Boolean -->
<my-element [disabled]="isDisabled"></my-element>

Angular maps [camelCase] property bindings to the element's camelCase properties. For kebab-case attributes, use [attr.kebab-case]:

<!-- Property: sets el.complexData -->
<my-element [complexData]="value"></my-element>

<!-- Attribute: sets el.setAttribute('aria-label', value) -->
<my-element [attr.aria-label]="label"></my-element>
Event Handling

Angular's (event) syntax works with custom element events:

<!-- Listen to custom events -->
<my-element (my-event)="handleEvent($event)"></my-element>

<!-- Access detail inline -->
<my-element (change)="value = $any($event).detail.value"></my-element>

For TypeScript, cast the event to the correct type of the event based on the manifest.

handleCustomEvent(event: CustomEvent<{ value: string }>) {
  this.value = event.detail.value;
}

// manifest has "type": { "text": "TypedInManifestEvent", "source": ... }
handleTypedInManifestEvent(event: TypedInManifestEvent) {
  this.value = event.detail.value;
}
Slots

Use the native HTML slot attribute:

<my-element>
  <!-- Default slot -->
  <span>Default content</span>

  <!-- Named slots -->
  <div slot="header">Header content</div>
  <div slot="footer">Footer content</div>
</my-element>

Angular content projection (<ng-content>) and web component slots are different mechanisms. Use slot="name" for web component slots.

Angular Forms Integration

Custom elements don't work with Angular's ngModel or reactive forms out of the box. Create a ControlValueAccessor:

import { Directive, ElementRef, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Directive({
  selector: 'my-input[formControlName], my-input[ngModel], my-input[formControl]',
  standalone: true,
  host: {
    '(input)': 'onInput($event)',
    '(blur)': 'onTouched()',
  },
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => MyInputValueAccessor),
      multi: true,
    },
  ],
})
export class MyInputValueAccessor implements ControlValueAccessor {
  private onChange: (value: any) => void = () => {};
  onTouched: () => void = () => {};

  constructor(private el: ElementRef<HTMLElement>) {}

  writeValue(value: any): void {
    (this.el.nativeElement as any).value = value;
  }

  registerOnChange(fn: (value: any) => void): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    (this.el.nativeElement as any).disabled = isDisabled;
  }

  onInput(event: Event): void {
    const value = (event as CustomEvent).detail?.value
      ?? (event.target as any).value;
    this.onChange(value);
  }
}

Then import the directive alongside the component:

@Component({
  standalone: true,
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  imports: [ReactiveFormsModule, MyInputValueAccessor],
  template: `<my-input [formControl]="nameControl"></my-input>`,
})
export class MyFormComponent {
  nameControl = new FormControl('');
}

Be sure to check the element descriptions for indication if it is a Form-Associated Custom Element (FACE).

TypeScript Declarations

Extend the HTMLElementTagNameMap so Angular's template type checker understands the elements:

// custom-elements.d.ts
declare global {
  interface HTMLElementTagNameMap {
    'my-element': import('my-element-library').MyElement;
  }
}

For stricter typing in templates, combine with CUSTOM_ELEMENTS_SCHEMA — Angular won't type-check custom element bindings by default when the schema is present.

Phase 5: Output

Present the integration with:

  1. Schema configuration appropriate to standalone vs NgModule style
  2. Usage examples for each element
  3. Property binding showing [property] vs [attr.attribute]
  4. Event handling with proper CustomEvent typing
  5. Slot usage with native slot attribute
  6. Forms integration if the element is form-associated (has value/input patterns)

Guidelines

  • Always include CUSTOM_ELEMENTS_SCHEMA: Without it, Angular throws template errors for unknown elements
  • Use [property] binding, not attr.: Angular's property binding sets properties directly, which custom elements handle correctly
  • Cast events to CustomEvent: Angular's template type system doesn't know about CustomEvent.detail
  • Don't confuse ng-content with slot: Angular content projection and web component slots are separate systems
  • ControlValueAccessor is required for forms: Without it, ngModel and reactive forms won't work with custom elements
  • Check for CUSTOM_ELEMENTS_SCHEMA in tests: Test modules/components need the schema too

Set Up CEM Serve for Development

Configure and run cem serve to preview custom elements with live reload, auto-generated import maps, and interactive knobs.

Best Practices

Package Dependencies

Runtime imports must be in dependencies, not devDependencies. The import map generator only resolves packages from dependencies.

{
  "dependencies": {
    "lit": "^3.0.0"
  },
  "devDependencies": {
    "@pwrs/cem": "^0.9.0"
  }
}

Project Config

Create .config/cem.yaml with generate and serve sections:

generate:
  files:
    - elements/*/my-*.ts
  output: custom-elements.json
  designTokens:
    spec: tokens/my-tokens.json
    prefix: my-prefix
  demoDiscovery:
    fileGlob: elements/*/demo/*.html
    urlPattern: /elements/:tag/demo/:demo.html
    urlTemplate: /elements/{{.tag}}/demo/{{.demo}}/
serve:
  transforms:
    css:
      include:
        - "elements/**/*.css"
  • generate.files: globs for element source files
  • generate.output: manifest output path
  • generate.designTokens: DTCG token file and CSS custom property prefix
  • generate.demoDiscovery: how to find and route demo files
  • serve.transforms.css.include: globs for CSS files to serve as JS modules (enables import styles from './el.css' with { type: 'css' })

Demo Files

Demos are HTML partials, not full documents. No <!DOCTYPE>, <html>, or <head>. Include inline <script type="module"> and <style> as needed.

The index.html demo is the default — keep it minimal (simplest possible usage). Additional demos show specific features or variants.

Use <meta itemprop="name"> and <meta itemprop="description"> on non-index demos for display in the dev server UI.

For demo authoring conventions, see the write-demos skill.

Testing with Chromeless Mode

cem serve --rendering=chromeless strips the dev server UI, serving bare demo HTML with import maps and transforms — ideal for browser-based testing with Playwright or Puppeteer. Append ?rendering=chromeless to any demo URL for per-request chromeless mode without restarting.

See the gen-tests skill for full test scaffolding with page objects against chromeless demos.

Workflow

1. Generate the Manifest

cem generate

Verify demos appear without warnings. If you see "No URL configured for demo", check that demoDiscovery.urlPattern uses URLPattern syntax (:param captures, not regex).

2. Start the Server

cem serve

Default port is 8000. Use --port <n> to change.

3. Verify

Open http://localhost:8000. The UI should show element demos in the sidebar. Check browser console for import errors — if a bare specifier fails, the package needs to be in dependencies.

Troubleshooting

Bare specifier errors

Move the package from devDependencies to dependencies and reinstall.

Duplicate demo route warnings

Delete the cached manifest and regenerate: rm custom-elements.json && cem generate

Port in use

lsof -ti:8000 | xargs kill or use --port.

Stale manifest on background regen

cem serve regenerates the manifest in the background on file changes. If the background regen produces a smaller/empty manifest, ensure generate.files in the config matches your source globs — the background regen uses the config, not CLI args.

Component Composition Advisor

Given a UI goal, recommend which custom elements to use together and generate composed HTML.

Workflow

Phase 1: Understand the Goal

Clarify (if not already provided):

  1. What UI is the user trying to build? (e.g., "login form", "data table", "card grid")
  2. Any constraints? (e.g., specific elements they must use, layout requirements)
  3. What level of detail? (quick wireframe-level vs production-ready)

Phase 2: Survey Available Elements

Read the complete element library:

cem://elements

Read project-level guidelines for composition patterns:

cem://guidelines

For each candidate element, read its full API to understand capabilities and slot expectations:

cem://element/{tagName}
cem://element/{tagName}/slots
cem://element/{tagName}/attributes

Phase 3: Select Elements

Choose elements based on:

Semantic Fit
  • Does the element's purpose match the role it would play in the composition?
  • Is the element designed for this kind of content?
Slot Compatibility
  • Can the elements nest correctly via slots?
  • Do parent element slots accept the kind of content the child elements produce?
  • Are there slot content guidelines that constrain composition?
Attribute Harmony
  • Do the elements share compatible attribute patterns?
  • Can they be configured to work together without conflicts?
  • Do variant/size attributes compose sensibly?
Event Flow
  • Can parent elements respond to child element events?
  • Is the event propagation path logical?

Phase 4: Generate Composed HTML

For each element in the composition, call generate_html to produce valid markup, then combine them.

Present the composition as:

## Composition: [UI Goal]

### Elements Used

| Element          | Role       | Why                                    |
|------------------|------------|----------------------------------------|
| `<prefix-card>`  | Container  | Provides visual grouping and elevation |
| `<prefix-input>` | Form field | Text input with built-in validation    |


### HTML

[Complete composed HTML with comments explaining structure]

### How It Works
- [Explain the composition: which elements are slotted where]
- [Note any attribute interactions between elements]
- [Describe the event flow for interactive compositions]

### Styling

[CSS showing how to style the composition, using CSS custom properties and parts from the composed elements]

### Alternatives Considered
- [Other element combinations that could work, and why this one is better]

Phase 5: Validate

Call validate_html on the final composed HTML to verify:

  • All elements are used correctly
  • Slot content follows guidelines
  • No attribute conflicts
  • Accessibility patterns are maintained

Report any issues and fix them before presenting the final result.

Guidelines

  • Prefer composition over customization: Use multiple elements together rather than forcing one element to do everything
  • Respect slot guidelines: If a slot says "text content only", don't put a complex element in it
  • Keep nesting shallow: Deeply nested compositions are fragile and hard to style
  • Show the minimal composition first: Start simple, then offer enhanced versions with more elements
  • Consider responsive behavior: Note if the composition needs different structure at different viewport sizes
  • Document the "why": Explain why each element was chosen so the user can make substitutions

Element API Design

Guide the design of a custom element's public API, ensuring consistency with existing elements and CEM conventions.

Workflow

Phase 1: Understand the Element

Ask the user (if not already provided):

  1. What is the element's purpose?
  2. What content does it render or contain?
  3. What interactions does it support?
  4. Are there existing elements it should be consistent with?

Phase 2: Survey Existing Conventions

Read the existing elements to understand naming patterns:

cem://elements

For elements the user mentions as related or similar, read their full APIs:

cem://element/{tagName}

Also read any project-level guidelines:

cem://guidelines

Note existing patterns for:

  • Tag naming: prefix conventions, naming style
  • Attribute naming: kebab-case patterns, boolean naming (e.g. disabled vs is-disabled)
  • Event naming: prefix patterns, past tense vs present
  • Slot naming: header, footer, actions patterns
  • CSS part naming: conventions for internal structure
  • CSS custom property naming: --element-property patterns

Phase 3: Design the API

Work through each API surface systematically:

Tag Name
  • Follow the project's tag prefix convention
  • Name should describe what the element is, not what it does
  • Avoid overly generic names
Attributes & Properties
  • Use kebab-case for attribute names
  • Use camelCase for corresponding property names
  • Boolean attributes should be positive (disabled, not enabled)
  • Enum attributes should list all valid values
  • Consider which attributes reflect to properties and vice versa
  • Provide sensible defaults
  • Document type constraints
  • Prefer CSS states to reflected state attributes
Slots
  • Use the default slot for primary content
  • Name slots by their semantic role (header, actions), not position (top, bottom)
  • Write content guidelines for each slot
  • Consider what content types are appropriate
Events
  • Name events in past tense for state changes (opened, closed)
  • Name events in present tense for ongoing actions (input, scroll)
  • Use the element prefix if events could conflict with native events
  • Design event detail types with the minimum necessary data
  • Document what triggers each event
  • Prefer to subclass Event for type safety, rather than to ship CustomEvent
CSS Custom Properties
  • Follow --element-name-property naming convention
  • Provide defaults that work in both light and dark themes
  • Group related properties (color, spacing, typography)
  • Consider which properties consumers will most likely want to override
  • Prefer to use existing design tokens rather than to add element-specific props
CSS Nesting
  • Use native CSS nesting for descendant selectors within shadow DOM
  • Don't nest :host attribute selectors with & -- &([attr]) inside :host {} is invalid because & substitutes :host literally, making &([attr]) parse as a function call rather than an attribute selector
  • Keep :host([variant="..."]) blocks flat at the top level; nesting is valid for descendants within those blocks
/* WRONG: &([attr]) is invalid */
:host {
  &([variant="primary"]) { ... }
}

/* RIGHT: flat :host selectors, nested descendants */
:host([variant="primary"]) {
  --_color: blue;
}

:host([variant="primary"]) button {
  &:hover { --_color: darkblue; }
  &:active { --_color: navy; }
}
CSS Parts
  • Name parts after the internal element they expose (button, label, icon)
  • Only expose parts that consumers need to style
  • Don't expose implementation details that may change
CSS States
  • Use custom states for element-specific states (:state(loading), :state(empty))
  • Map to existing CSS pseudo-classes where appropriate
  • Document state transitions

Phase 4: Source Documentation

When presenting the designed API, show how each part should be documented in source code.

!cat ${CLAUDE_SKILL_DIR}/html-comment-syntax.md

Phase 5: Consistency Check

Compare the proposed API against existing elements:

  • Are similar concepts named the same way?
  • Do shared attribute names have compatible types?
  • Are event patterns consistent?
  • Do CSS property names follow the same scheme?

Phase 6: Output

Present the designed API as a structured summary:

## `<prefix-element-name>` API Design

### Description
[One-paragraph purpose statement]

### Attributes
| Name | Type | Default | Description |
|------|------|---------|-------------|
| `variant` | `'primary' \| 'secondary'` | `'primary'` | Visual style variant |

### Slots
| Name | Description | Content Guidelines |
|------|-------------|--------------------|
| (default) | Primary content | Text or inline elements |

### Events

| Name | Type | Description |
|------|-------------|-------------|
| `change` | `MyChangeEvent` | Fired when value changes |

### CSS Custom Properties
| Name | Default | Description |
|------|---------|-------------|
| `--prefix-element-color` | `light-dark(#000, #fff)` | Primary text color |

### CSS Parts
| Name | Description |
|------|-------------|
| `button` | The internal button element |

### CSS States
| Name | Description |
|------|-------------|
| `loading` | Applied while async content loads |

Optionally, generate a skeleton class definition or manifest snippet if the user wants to start implementing.

Design Principles

  • Minimal API surface: Don't add attributes "just in case" — each should serve a clear purpose
  • Consistency over novelty: Match existing patterns in the project, even if you'd name things differently in isolation
  • Attributes for HTML, properties for JS: Attributes should be serializable; complex data goes through properties only
  • Slots over attributes for rich content: If content could be more than a plain string, use a slot
  • CSS custom properties for theming, parts for structure: Properties for colors/spacing, parts for layout overrides
  • Clarify: If an API can't be clearly and succinctly described in plain English, that likely indicates a design flaw.

Documentation Health Check

Audit custom element manifests for documentation completeness and quality using cem health.

Workflow

Phase 1: Run Health Analysis

Run cem health with JSON output to get structured scoring data:

cem health --format json

To filter to specific components or modules:

# Single component
cem health --format json --component my-button

# Specific modules
cem health --format json --module src/components/button.js

The JSON output has this structure:

{
  "modules": [
    {
      "path": "src/components/button.js",
      "score": 18,
      "maxScore": 20,
      "declarations": [
        {
          "tagName": "my-button",
          "name": "MyButton",
          "score": 18,
          "maxScore": 20,
          "categories": [
            {
              "id": "description",
              "category": "Description",
              "points": 5,
              "maxPoints": 5,
              "status": "pass",
              "findings": [...]
            },
            {
              "id": "attributes",
              "category": "Attribute Documentation",
              "points": 3,
              "maxPoints": 5,
              "status": "warn",
              "findings": [
                {
                  "check": "attribute 'variant' has description",
                  "points": 1,
                  "max": 1
                },
                {
                  "check": "attribute 'size' has description",
                  "points": 0,
                  "max": 1,
                  "message": "Add a description for attribute 'size'"
                }
              ]
            }
          ]
        }
      ]
    }
  ],
  "overallScore": 18,
  "overallMax": 20,
  "recommendations": [
    "my-button: Add a description for attribute 'size' (Attribute Documentation, +1 pts)"
  ]
}

Phase 2: Interpret Results

The health categories scored by cem health are:

CategoryWhat it checks
descriptionElement has a description and summary
attributesEvery attribute has a description, type, and default
slotsEvery slot has a description
cssCSS custom properties, parts, and states have descriptions
eventsEvery event has a description and type
demosElement has demo links

Status values:

  • pass (>=80%): Well documented
  • warn (40-79%): Has gaps
  • fail (<40%): Major gaps

Phase 3: Report

Present the results in a readable format. Use the JSON data to build:

## Documentation Health Report

### Summary
- Components audited: X
- Overall score: X/Y (Z%)
- Components passing: X
- Components needing attention: X

### Per-Component Scores

| Component | Score | Description | Attrs | Slots | Events | CSS | Demos |
|-----------|-------|-------------|-------|-------|--------|-----|-------|
| `<my-button>` | 90% | pass | pass | pass | warn | pass | fail |

### Findings

#### `<my-button>` (18/20, 90%)
- **Attribute Documentation** (warn): Add a description for attribute 'size'
- **Demos** (fail): No demo links found

### Top Recommendations
[List the recommendations from the JSON output — these are already
sorted by point impact]

Phase 4: Deeper Investigation (Optional)

If the user wants more detail on specific gaps, read the element's MCP resources:

cem://element/{tagName}
cem://element/{tagName}/attributes
cem://element/{tagName}/slots

This provides the full manifest data so you can show exactly what's missing and suggest what to document.

Phase 5: Suggesting Fixes

When reporting gaps, show the user how to fix them.

!cat ${CLAUDE_SKILL_DIR}/html-comment-syntax.md

Guidelines

  • Use cem health as the source of truth: Don't reinvent the scoring — it already checks descriptions, types, defaults, etc.
  • Surface recommendations first: The recommendations array is sorted by impact — present those prominently
  • Suggest, don't fabricate: Flag gaps for the element author to fill, don't invent descriptions
  • Flag inconsistencies: If some elements score 100% and others score 30%, highlight the gap
  • Use --component for focused audits: When the user asks about a specific element, filter to avoid noise

Test Scaffolding Generator

Generate browser-based test scaffolding for custom elements using the Page Object Model pattern, testing against cem serve's chromeless demo UI with Playwright or Puppeteer.

Workflow

Phase 1: Gather Element Data

Read the target element's full manifest data:

cem://element/{tagName}
cem://element/{tagName}/attributes
cem://element/{tagName}/slots
cem://element/{tagName}/events
cem://element/{tagName}/css/parts
cem://element/{tagName}/css/custom-properties
cem://element/{tagName}/css/states

Check which demos exist for the element — the manifest's demos array defines the available demo pages and their URLs.

Phase 2: Detect Test Environment

Search the project for existing test patterns:

  1. Look for existing test files to match conventions:

    • *.test.ts, *.spec.ts patterns
    • Test framework: Playwright (@playwright/test) or Puppeteer (puppeteer)
    • Existing playwright.config.ts or puppeteer setup
    • Existing page objects in tests/pages/, tests/models/, etc.
  2. Check package.json for test dependencies and scripts

  3. If no test framework is present, recommend Playwright and generate a config

Phase 3: Generate Playwright Config (if needed)

If the project doesn't have a Playwright config, generate one that starts cem serve in chromeless mode:

// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  webServer: {
    command: 'cem serve --rendering=chromeless',
    port: 8000,
    reuseExistingServer: !process.env.CI,
  },
  use: {
    baseURL: 'http://localhost:8000',
  },
});

For Puppeteer, generate equivalent setup/teardown that spawns cem serve.

Phase 4: Generate Page Object

Generate a page object class for the element that encapsulates all locators and interactions derived from the manifest. The page object is the primary output — tests become thin and readable when the page object does the work.

Page Object Structure
// tests/pages/MyButtonPage.ts
import type { Locator, Page } from '@playwright/test';

export class MyButtonPage {
  readonly page: Page;

  /** The <my-button> element */
  readonly host: Locator;

  // --- Slots (from manifest slots) ---

  /** Default slot content */
  readonly slotDefault: Locator;
  /** The icon slot */
  readonly slotIcon: Locator;

  constructor(page: Page) {
    this.page = page;
    this.host = page.locator('my-button');
    this.slotDefault = this.host.locator('> :not([slot])');
    this.slotIcon = this.host.locator('[slot="icon"]');
  }

  // --- Navigation ---

  async goto(demo = '') {
    const path = demo
      ? `/elements/my-button/demo/${demo}`
      : '/elements/my-button/demo/';
    await this.page.goto(path);
  }

  // --- Attribute helpers (from manifest attributes) ---

  async variant(): Promise<string | null> {
    return this.host.getAttribute('variant');
  }

  async setVariant(value: 'primary' | 'secondary' | 'danger') {
    await this.host.evaluate((el, v) => el.setAttribute('variant', v), value);
  }

  async disabled(): Promise<boolean> {
    return this.host.evaluate((el) => el.hasAttribute('disabled'));
  }

  async setDisabled(value: boolean) {
    await this.host.evaluate(
      (el, v) => el.toggleAttribute('disabled', v),
      value,
    );
  }

  // --- Property helpers (for non-attribute properties) ---

  async setComplexData(value: unknown) {
    await this.host.evaluate((el, v) => (el as any).complexData = v, value);
  }

  // --- Event helpers (from manifest events) ---

  /**
   * Returns a promise that resolves with serializable event data when the
   * element fires the given event. Call this BEFORE triggering the interaction.
   *
   * DOM Event objects are not serializable across the Playwright boundary.
   * This extracts the event's own enumerable properties (the class fields
   * on typed Event subclasses) into a plain object.
   */
  async waitForEvent(eventName: string): Promise<Record<string, unknown>> {
    return this.host.evaluate(
      (el, name) =>
        new Promise<Record<string, unknown>>((resolve) =>
          el.addEventListener(
            name,
            (ev) => {
              const data: Record<string, unknown> = { type: ev.type };
              for (const key of Object.keys(ev)) {
                data[key] = (ev as Record<string, unknown>)[key];
              }
              resolve(data);
            },
            { once: true },
          ),
        ),
      eventName,
    );
  }

  // --- CSS helpers (from manifest CSS custom properties) ---

  async setCssProperty(name: string, value: string) {
    await this.host.evaluate(
      (el, [n, v]) => el.style.setProperty(n, v),
      [name, value] as const,
    );
  }

  async computedStyle(property: string, internalSelector?: string): Promise<string> {
    return this.host.evaluate(
      (el, [prop, selector]) => {
        const target = selector
          ? el.shadowRoot?.querySelector(selector) ?? el
          : el;
        return getComputedStyle(target).getPropertyValue(prop);
      },
      [property, internalSelector ?? null] as const,
    );
  }

  // --- State helpers (from manifest CSS states) ---

  async matchesState(state: string): Promise<boolean> {
    return this.host.evaluate((el, s) => el.matches(`:state(${s})`), state);
  }

  // --- Interaction helpers ---

  async click() {
    await this.host.click();
  }

  async focus() {
    await this.host.focus();
  }
}
Page Object Generation Rules

For each manifest feature, generate the corresponding page object members:

Manifest FeaturePage Object Member
Each attributeGetter method + setter method (typed for enums)
Each property (no attribute)Setter via evaluate
Each named slotLocator field: this.host.locator('[slot="name"]')
Default slotLocator field: this.host.locator('> :not([slot])')
Each CSS partHelper method using evaluate to query shadow root
Each CSS custom propertyHelper via setCssProperty / computedStyle
Each CSS statematchesState(name) boolean helper
Each eventTyped waitForEvent usage or dedicated method
Each demo URLNamed navigation method or param to goto()

Phase 5: Generate Test Cases

Tests use the page object — they should read almost like plain English.

// tests/my-button.spec.ts
import { test, expect } from '@playwright/test';
import { MyButtonPage } from './pages/MyButtonPage';

test.describe('<my-button>', () => {
  let button: MyButtonPage;

  test.beforeEach(async ({ page }) => {
    button = new MyButtonPage(page);
    await button.goto();
  });

  test.describe('attributes', () => {
    test('has primary variant by default', async () => {
      await expect(button.host).toHaveAttribute('variant', 'primary');
    });

    test('reflects variant attribute', async () => {
      await button.setVariant('secondary');
      await expect(button.host).toHaveAttribute('variant', 'secondary');
    });

    test('supports all variant values', async () => {
      for (const variant of ['primary', 'secondary', 'danger'] as const) {
        await button.setVariant(variant);
        await expect(button.host).toHaveAttribute('variant', variant);
      }
    });

    test('toggles disabled', async () => {
      expect(await button.disabled()).toBe(false);
      await button.setDisabled(true);
      expect(await button.disabled()).toBe(true);
    });
  });

  test.describe('slots', () => {
    test('projects default slot content', async () => {
      await expect(button.slotDefault.first()).toBeVisible();
    });

    test('projects icon slot content', async () => {
      // Only test if the demo includes icon slot content
      await expect(button.slotIcon).toBeAttached();
    });
  });

  test.describe('events', () => {
    test('fires change event', async () => {
      const eventData = button.waitForEvent('change');
      await button.setVariant('secondary');
      expect((await eventData).type).toBe('change');
    });
  });

  test.describe('css custom properties', () => {
    test('--my-button-color overrides text color', async () => {
      await button.setCssProperty('--my-button-color', 'red');
      const color = await button.computedStyle('color', '#button');
      expect(color).toBe('rgb(255, 0, 0)');
    });
  });

  test.describe('css states', () => {
    test('matches :state(loading) when loading', async () => {
      await button.host.evaluate((el: any) => (el.loading = true));
      expect(await button.matchesState('loading')).toBe(true);
    });
  });

  test.describe('accessibility', () => {
    test('has button role', async () => {
      await expect(button.host).toHaveRole('button');
    });

    test('is keyboard focusable', async ({ page }) => {
      await page.keyboard.press('Tab');
      await expect(button.host).toBeFocused();
    });
  });

  test.describe('visual regression', () => {
    test('default appearance', async () => {
      await expect(button.host).toHaveScreenshot('my-button-default.png');
    });
  });
});

Phase 6: File Layout

Generate both files:

tests/
├── pages/
│   └── MyButtonPage.ts       # Page object
└── my-button.spec.ts          # Test cases

Or match the project's existing test directory structure if one exists.

Chromeless Demo Reference

cem serve provides a chromeless rendering mode designed for testing:

  • Start: cem serve --rendering=chromeless
  • Demo URL: http://localhost:8000/elements/{tag-name}/demo/
  • What it provides: Bare demo HTML with live reload, import maps, and TypeScript/CSS transforms — no nav, knobs panel, or dev server UI
  • Query param override: Append ?rendering=chromeless to any demo URL to get chromeless mode even when the server runs in default mode

Guidelines

  • Always generate a page object: The page object is the main deliverable — tests should be thin wrappers
  • One page object per element: Named {PascalCaseTag}Page (e.g., MyButtonPage)
  • Type attribute setters with manifest enums: If variant accepts 'primary' | 'secondary', type the setter parameter
  • Default to Playwright: Unless the project already uses Puppeteer
  • Navigate to real demos: Use the element's actual demo pages, not blank pages with manually constructed HTML
  • Test behavior, not implementation: Test the public API via the browser, not internal DOM structure
  • One assertion per test (where practical): Makes failures easy to diagnose
  • Descriptive test names: 'reflects the variant attribute' not 'works'
  • Mark TODOs: Where the manifest doesn't provide enough info to write a complete assertion, add a // TODO: comment explaining what to fill in
  • Don't over-generate: Skip categories that don't apply (e.g., no CSS state tests if the element has no custom states, no slot tests if no slots)
  • Use demo variants: If the manifest has multiple demos, test the relevant variant for each feature (e.g., test loading state against a loading demo)
  • For Puppeteer: Adapt the page object to use page.$eval, page.waitForSelector, etc. instead of Playwright locators, but keep the same class structure and method names

Migration Assistant

Compare custom element manifests across versions to identify breaking changes and generate migration guidance.

Workflow

Phase 1: Identify Versions to Compare

Determine the two versions to compare. Sources:

  1. Git-based: Compare the current manifest against a previous git ref

    git show {ref}:path/to/custom-elements.json
    
  2. File-based: User provides two manifest files or paths

  3. Package-based: Compare installed version against a target version

    • Read current manifest from node_modules/{package}/custom-elements.json
    • Check the target version's manifest

Read the current project's elements for context:

cem://elements

Phase 2: Diff Analysis

Compare the two manifests and categorize changes:

Removed (Breaking)
  • Removed elements: Tag names that no longer exist
  • Removed attributes: Attributes dropped from an element
  • Removed slots: Named slots that no longer exist
  • Removed events: Events that are no longer fired
  • Removed CSS parts: Parts no longer exposed
  • Removed CSS custom properties: Theming properties removed
Changed (Potentially Breaking)
  • Renamed attributes: Attribute name changed (detect via similar names + same type)
  • Type changes: Attribute type changed (e.g., string to enum, boolean to string)
  • Enum value changes: Valid values added or removed
  • Default value changes: Different default behavior
  • Slot renamed: Named slot changed (detect via similar names)
  • Event detail changes: Event detail type modified
  • CSS property renamed: Custom property name changed
Added (Non-Breaking)
  • New elements: Newly available tag names
  • New attributes: Additional configuration options
  • New slots: Additional content areas
  • New events: Additional observable state changes
  • New CSS parts/properties/states: Additional styling hooks
Deprecated
  • Deprecated attributes: Marked for future removal
  • Deprecated elements: Elements scheduled for removal
  • Look for deprecated field or deprecation notes in descriptions

Phase 3: Impact Assessment

For each breaking change, search the project for affected usage:

  • Search HTML files for removed/changed element tag names
  • Search for removed attribute names on affected elements
  • Search for removed event listeners
  • Search CSS for removed parts and custom properties

Report the number of affected files and locations.

Phase 4: Migration Report

## Migration Report: {package} {old-version} -> {new-version}

### Summary
- Breaking changes: X
- Potentially breaking: X
- New features: X
- Deprecations: X
- Files affected: X

### Breaking Changes

#### 1. `<old-element>` removed
**Impact**: Used in X files
**Migration**: Replace with `<new-element>`
```diff
- <old-element attr="value">content</old-element>
+ <new-element attr="value">content</new-element>
```
**Files affected**:
- `src/pages/login.html:15`
- `src/components/form.html:42`

#### 2. `variant` attribute on `<prefix-button>` renamed to `appearance`
**Impact**: Used in X files
**Migration**: Rename the attribute
```diff
- <prefix-button variant="primary">
+ <prefix-button appearance="primary">
```

### Deprecation Warnings

[Items that still work but will break in a future version]

### New Features

[Brief summary of what's new — the user might want to adopt these]

### Recommended Migration Order

1. [Fix breaking changes that cause build/runtime errors first]
2. [Address deprecation warnings]
3. [Optionally adopt new features]

Guidelines

  • Be conservative with "renamed" detection: Only suggest a rename if the types match and names are similar — don't guess
  • Show concrete diffs: Every breaking change should include a before/after code example
  • Find all affected files: Don't just describe the change abstractly — show where it matters in the project
  • Distinguish runtime breaks from cosmetic changes: A removed attribute is worse than a changed default
  • Suggest incremental migration: If there are many changes, recommend an order that keeps the project functional at each step

Custom Elements in React

Generate framework-specific guidance for using custom elements in React, adapting to the project's React version.

Workflow

Phase 1: Detect React Version

Search the project for React version:

# Check package.json for react version
grep -A1 '"react"' package.json

Determine if the project uses:

  • React 19+: Native custom element support
  • React 18 or earlier: Requires workarounds for properties and events

Also check for:

  • TypeScript (need JSX type declarations)
  • Existing wrapper patterns in the codebase
  • Whether @lit/react or similar wrapper libraries are already in use

Phase 2: Gather Element Data

Read the target element(s):

cem://element/{tagName}
cem://element/{tagName}/attributes
cem://element/{tagName}/events

Understand the element's API to know which features need framework-specific handling:

  • Attributes (string-only): Work in all React versions
  • Properties (complex types): Need workarounds in React 18
  • Events (custom events): Need workarounds in React 18
  • Slots: Map to children and named slot patterns in JSX
  • Boolean attributes: Differ between React and HTML semantics

Phase 3: Generate Integration Code

React 19+

React 19 supports custom elements natively. Properties are set correctly and custom events are handled.

// Direct usage — no wrappers needed
function MyComponent() {
  return (
    <my-element
      variant="primary"
      complexData={someObject}
      onMyEvent={(e) => handleEvent(e)}
    >
      <span slot="icon">★</span>
      Button text
    </my-element>
  );
}

Key React 19 behaviors:

  • Props matching an element property are set as properties, not attributes
  • on + PascalCase event name maps to custom events (e.g., onChange -> change)
  • className is set as the class attribute
  • Boolean attributes work correctly
React 18 and Earlier

React 18 treats custom elements like unknown HTML elements — all props are set as attributes (stringified), and custom events are not supported via JSX.

Option A: Use @lit/react wrappers (recommended)

import { createComponent } from '@lit/react';
import { MyElement } from 'my-element-library';

export const MyElementReact = createComponent({
  tagName: 'my-element',
  elementClass: MyElement,
  react: React,
  events: {
    onMyEvent: 'my-event',
    onChange: 'change',
  },
});

// Usage
function MyComponent() {
  return (
    <MyElementReact
      variant="primary"
      complexData={someObject}
      onMyEvent={(e) => handleEvent(e)}
    >
      Button text
    </MyElementReact>
  );
}

Option B: Use refs for properties and events

function MyComponent() {
  const ref = useRef<HTMLElement>(null);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;

    // Set complex properties via ref
    (el as any).complexData = someObject;

    // Add event listeners
    const handler = (e: Event) => handleEvent(e);
    el.addEventListener('my-event', handler);
    return () => el.removeEventListener('my-event', handler);
  }, [someObject]);

  return (
    <my-element ref={ref} variant="primary">
      Button text
    </my-element>
  );
}

Option C: Use the CEM export react wrappers

If the project uses CEM's export command, check for pre-generated React wrappers:

cem export react

This generates typed React wrapper components from the manifest.

TypeScript Declarations

For both React versions, add JSX type declarations so TypeScript knows about custom element attributes:

// custom-elements.d.ts
import type { MyElement } from 'my-element-library';

declare global {
  namespace JSX {
    interface IntrinsicElements {
      'my-element': React.DetailedHTMLProps<
        React.HTMLAttributes<MyElement> & {
          variant?: 'primary' | 'secondary';
          disabled?: boolean;
          // For React 18: only string attributes here
          // For React 19: include property types too
        },
        MyElement
      >;
    }
  }
}

For React 19, the declaration can include complex property types. For React 18, only include attributes (strings/booleans) since complex types won't pass through correctly without a wrapper.

Slot Mapping

Map named slots to JSX:

// HTML slots -> JSX
<my-element>
  {/* Default slot */}
  <span>Default content</span>

  {/* Named slots */}
  <span slot="header">Header content</span>
  <span slot="footer">Footer content</span>
</my-element>

Phase 4: Output

Present the integration code with:

  1. Version-appropriate code: Only show React 19 patterns if the project uses React 19+
  2. TypeScript declarations: If the project uses TypeScript
  3. Event handling: For each event in the manifest
  4. Property passing: For each non-string property
  5. Import statements: Show how to import the element registration

React Version Reference

FeatureReact 18React 19+
String attributesPassed as attributesPassed as attributes
Boolean attributes"" or undefinedCorrect HTML behavior
Complex propertiesStringified (broken)Set as properties
Custom eventsNot supported in JSXonEventName works
classNameSet as attributeSet as class
refWorksWorks
SSRAttributes onlyAttributes only

Guidelines

  • Check the React version first: The guidance differs significantly between 18 and 19
  • Prefer @lit/react wrappers for React 18: They handle properties and events correctly with minimal boilerplate
  • Generate TypeScript declarations from the manifest: The element's attributes and their types are all available
  • Don't suggest dangerouslySetInnerHTML: Custom elements use slots, not innerHTML
  • Handle SSR: Note that server-rendered custom elements only have access to attributes, not properties

Custom Elements in Vue

Generate framework-specific guidance for using custom elements in Vue, including required compiler configuration.

Workflow

Phase 1: Detect Vue Version and Build Setup

Search the project for Vue version and tooling:

  • Check package.json for vue version (2.x vs 3.x)
  • Check for build tool: Vite (vite.config), Vue CLI (vue.config), Nuxt (nuxt.config), or webpack
  • Check for TypeScript usage
  • Check for existing custom element configuration

Phase 2: Gather Element Data

Read the target element(s):

cem://element/{tagName}
cem://element/{tagName}/attributes
cem://element/{tagName}/events
cem://element/{tagName}/slots

Understand which features need framework-specific handling:

  • Attributes vs properties: Vue can bind either with different syntax
  • Events: Vue's v-on / @ syntax works with custom events
  • Slots: Vue slots and web component slots interact
  • v-model: May need custom setup for two-way binding

Phase 3: Required Configuration

Vue 3 + Vite
// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
  plugins: [
    vue({
      template: {
        compilerOptions: {
          // Tell Vue to treat tags with a dash as custom elements
          isCustomElement: (tag) => tag.includes('-'),
        },
      },
    }),
  ],
});

If the project only uses elements from specific libraries, be more specific:

isCustomElement: (tag) => tag.startsWith('my-') || tag.startsWith('prefix-'),
Vue 3 + Vue CLI (webpack)
// vue.config.js
module.exports = {
  chainWebpack: (config) => {
    config.module
      .rule('vue')
      .use('vue-loader')
      .tap((options) => ({
        ...options,
        compilerOptions: {
          isCustomElement: (tag) => tag.includes('-'),
        },
      }));
  },
};
Nuxt 3
// nuxt.config.ts
export default defineNuxtConfig({
  vue: {
    compilerOptions: {
      isCustomElement: (tag) => tag.includes('-'),
    },
  },
});
Vue 2

Vue 2 uses Vue.config.ignoredElements:

// main.js
Vue.config.ignoredElements = [
  'my-element',
  /^prefix-/,  // regex for all elements with a prefix
];

Note: Vue 2 reached end-of-life on December 31, 2023. Consider migrating to Vue 3.

Phase 4: Generate Integration Code

Basic Usage
<template>
  <my-element
    variant="primary"
    :disabled="isDisabled"
    @my-event="handleEvent"
  >
    Default slot content
  </my-element>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import 'my-element-library';

const isDisabled = ref(false);

function handleEvent(e: CustomEvent) {
  console.log(e.detail);
}
</script>
Attribute vs Property Binding
<template>
  <!-- Attribute binding (string coercion) -->
  <my-element variant="primary" />

  <!-- Property binding (passes JS values directly) -->
  <my-element :complex-data="myObject" />
  <!-- or explicitly with .prop modifier -->
  <my-element :complex-data.prop="myObject" />

  <!-- Boolean attribute -->
  <my-element :disabled="true" />
  <!-- or just present for true -->
  <my-element disabled />
</template>

Vue 3 passes :bound values as properties if the element has a matching property, and as attributes otherwise. Use the .prop modifier to force property binding.

In Vue 2, use the .prop modifier explicitly:

<my-element :complex-data.prop="myObject" />
Event Handling

Vue's @ / v-on works with custom element events:

<template>
  <!-- kebab-case event names work directly -->
  <my-element @my-event="handleMyEvent" />

  <!-- Access event detail -->
  <my-element @change="(e) => value = e.detail.value" />
</template>

Note: Vue converts @myEvent to listen for my-event (camelCase to kebab-case). If the custom element fires a camelCase event name, use the explicit form:

<my-element v-on:myEvent="handler" />
Slots

Web component slots and Vue slots coexist but work differently:

Important: Do not use Vue's v-slot / #slotname syntax for web component slots. Use the native HTML slot="name" attribute instead.

<template>
  <my-element>
    <!-- Default slot -->
    <span>Content goes to the default slot</span>

    <!-- Named slots — use the native HTML slot attribute -->
    <span slot="header">This goes to the web component's header slot</span>
    <span slot="footer">This goes to the web component's footer slot</span>
  </my-element>
</template>
v-model

Custom elements don't support v-model out of the box. Wire it up manually:

<template>
  <my-input
    :value="inputValue"
    @input="inputValue = $event.detail.value"
  />
</template>

Or create a composable for reusable v-model binding:

function useCustomElementModel(eventName = 'input', detailKey = 'value') {
  return {
    modelValue: (props: any) => props.modelValue,
    listener: (emit: any) => (e: CustomEvent) => emit('update:modelValue', e.detail[detailKey]),
  };
}
TypeScript

Add type declarations for custom elements in Vue templates:

// custom-elements.d.ts
declare module 'vue' {
  interface GlobalComponents {
    'my-element': import('my-element-library').MyElement;
  }
}

For more detailed type checking, use the element's type with Vue's HTMLAttributes:

declare module 'vue' {
  interface GlobalComponents {
    'my-element': DefineComponent<{
      variant?: 'primary' | 'secondary';
      disabled?: boolean;
    }>;
  }
}

Phase 5: Output

Present the integration with:

  1. Required config appropriate to the project's build tool
  2. Usage examples for each element the user asked about
  3. Property binding for complex (non-string) properties
  4. Event handling for each event in the manifest
  5. Slot usage with the correct native slot attribute (not Vue v-slot)
  6. TypeScript declarations if the project uses TypeScript

Guidelines

  • Always include the isCustomElement config: Without it, Vue warns about unresolved components
  • Use native slot attribute, not v-slot: This is the most common mistake when using web components in Vue
  • Prefer :prop binding for non-strings: Vue's property binding passes values correctly to custom elements
  • Check for Nuxt: Nuxt has its own config location for compiler options
  • Note Vue 2 EOL: If the project uses Vue 2, mention the EOL status but still provide working guidance

Write Element Demos

Critical: Demos Are Partials

Never include <!DOCTYPE>, <html>, <head>, or <body>. The dev server wraps partials with its own document shell, import maps, and live reload. Adding document structure breaks rendering.

Workflow

1. Gather Context

Read the element's manifest data (cem://element/{tagName} and sub-resources) and check .config/cem.yaml for:

  • generate.demoDiscovery — fileGlob determines where demos live; urlPattern captures path segments with :param; urlTemplate builds served URLs from those params (supports alias, slug, lower, upper template functions). Example: elements/rh-card/demo/sizes.html with urlTemplate: /elements/{{.tag | alias}}/demo/{{.demo}}/ serves at /elements/card/demo/sizes/. Index demos become the directory root.
  • serve.urlRewrites (if present) — maps served URLs back to filesystem paths when they differ (e.g., /elements/card/... to /elements/rh-card/...). Most projects don't need this. Check if configured, and set up if asked.
  • serve.importMap — bare specifiers need to be in dependencies or the import map config

2. Write Demos

Place files where fileGlob expects them (typically elements/my-el/demo/).

Index demo — simplest possible usage, no metadata needed:

<script type="module">
  import '../my-button.js';
</script>

<my-button>Click Me</my-button>

Feature demos — one feature per file, with metadata:

<meta itemprop="name"
      content="With Icon">
<meta itemprop="description"
      content="Button with a leading icon in the icon slot">

<script type="module">
  import '../my-button.js';
  import '../../my-icon/my-icon.js';
</script>

<my-button variant="primary">
  <my-icon slot="icon"
           name="check"></my-icon>
  Save Changes
</my-button>

Multi-element demos — use demo-for to associate with specific elements:

<meta itemprop="demo-for"
      content="my-button my-icon">

3. Validate

Call validate_html on the demo content, then verify:

  • No document shell tags
  • Script imports resolve (relative paths from demo file to source)
  • <meta> tags use itemprop, not name or property

Common Mistakes

MistakeFix
Adding <!DOCTYPE> / <html>Demos are partials
<meta name="description"><meta itemprop="description">
Absolute import pathsRelative from demo file to source
Importing from devDependenciesMove to dependencies
External CSS/JS linksInline styles and scripts
Everything in one fileOne feature per demo
Missing type="module"Always <script type="module">

Guidelines

  • Index is minimal: default demo should be copy-paste simple
  • Self-contained: inline all CSS and JS
  • One feature per file: variants, states, features get separate demos
  • Use generate_html: produce valid element markup via the MCP tool

Write Element Documentation

Generate documentation for custom elements based on their manifest API surface, including usage examples and integration guidance.

Workflow

Phase 1: Gather Element Data

Read the target element's full manifest data:

cem://element/{tagName}

And each sub-resource for complete coverage:

cem://element/{tagName}/attributes
cem://element/{tagName}/slots
cem://element/{tagName}/events
cem://element/{tagName}/css/parts
cem://element/{tagName}/css/custom-properties
cem://element/{tagName}/css/states

Also read project-level guidelines for tone and conventions:

cem://guidelines

Phase 1b: Source Comment Syntax

!cat ${CLAUDE_SKILL_DIR}/html-comment-syntax.md

Phase 2: Detect Documentation Conventions

Search the project for existing documentation patterns:

  1. Look for existing docs files to match format and structure:

    • Markdown docs in docs/, documentation/, or alongside source
    • Storybook stories (*.stories.ts, *.stories.js)
    • README files in component directories
    • JSDoc/TSDoc in source files, including CSS files
  2. Match the project's existing doc style:

    • Heading structure and depth
    • Code example format (HTML-only, with JS, framework-specific)
    • Whether docs include live demos or static examples
    • Tone (formal API reference vs conversational guide)

Phase 3: Generate Documentation

Element Overview
  • Purpose statement from the manifest description
  • When to use this element (and when not to)
  • Quick start example showing the simplest useful usage
Usage Examples

Generate HTML examples using generate_html for:

  • Basic usage: Minimal attributes, default slot content
  • Common configurations: Each major attribute combination
  • Slot variations: Each named slot with appropriate content
  • Composition: Element used with related elements from the same library
Attributes Reference
NameTypeDefaultDescription

For enum attributes, include a sub-table or list of valid values with descriptions.

Slots Reference
NameDescriptionContent Guidelines

Include example HTML showing content in each slot.

Events Reference
NameDetailDescription

Include JavaScript examples showing how to listen for and handle each event.

Styling

CSS Custom Properties:

PropertyDefaultDescription

CSS Parts:

PartDescription

CSS States:

StateDescription

Include a CSS example showing common customizations.

Accessibility

Document any manifest-sourced accessibility patterns:

  • ARIA role and keyboard interaction
  • Required content for screen readers
  • Focus management behavior

Phase 4: Output Format

Adapt the output format to match what the user needs:

  • Markdown: Default, suitable for docs sites or READMEs
  • HTML: If the project uses HTML documentation
  • Storybook: If stories exist, generate a *.stories.ts with knobs for each attribute

Ask the user which format they prefer if it's not clear from context.

Guidelines

  • Use manifest data as the source of truth: Don't invent behavior not documented in the manifest
  • Generate working examples: Call generate_html to produce valid HTML, don't hand-write examples that might have errors
  • Match existing tone: If the project's docs are terse, be terse. If they're tutorial-style, match that
  • Link to related elements: When composition makes sense, reference other elements from cem://elements
  • Mark uncertainty: If the manifest lacks enough detail for a section, note it rather than guessing
  • Docs feed the manifest: When writing JSDoc, remember it generates the manifest. Use @summary for the short description, @cssprop / @csspart / @slot / @fires for API docs. Well-written JSDoc produces a better manifest, which produces better MCP and LSP support.
  • Write MCP-effective descriptions: Descriptions should be concise, specific, and machine-readable. Avoid vague language. State what the attribute does, not just what it is. See the CEM guide on effective MCP descriptions.
  • Demo files are docs too: Each demo should show one variant or feature. Use <meta itemprop="name"> and <meta itemprop="description"> for demo metadata. Keep demos self-contained with inline imports.
  • Escape backticks in template HTML comments: HTML comments inside Lit html tagged template literals are used for slot/part docs. Backticks in these comments (e.g. `currentColor`) break cem's TS transform because they're parsed as template literal boundaries. Escape them with ``` or avoid them.

MCP servers 1

Sponsors

Details

Marketplace
bennypowers/cem
Source
extensions/claude-code
Author
Benny Powers
Category
Development
Keywords
custom-elements, web-components, html, typescript, javascript, lit, lsp, mcp