Lit

From j4flmao/agent-skills · View interactive version

Lit is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about Lit, LitElement, lit-html templates, reactive properties, Lit decorators, Lit context or Lit SSR. Produces typed Lit web components with shadow DOM styles and custom events. Not for framework-free custom elements (use frontend-web-components) or Stencil (use stencil).

How to use this skill

Skill file

Lit

Purpose

Build standard web components with Lit: reactive properties, shadow DOM templates, typed events, and SSR-compatible rendering.

Agent Protocol

Trigger

Exact user phrases: "Lit", "LitElement", "lit-html", "web component Lit", "reactive element", "@lit/reactive-element", "Lit SSR", "Lit component", "Lit decorator", "Lit reactive property".

Input Context

Before activating, verify:

Output Artifact

No file output. Produces component design, property configuration, template patterns, and SSR setup as text.

Response Format

Component: {name} — {purpose}
Properties: {reactive attributes/properties}
Template: {shadow DOM structure}
Events: {CustomEvent dispatch}

No preamble. No postamble. No explanations. No filler/hedging/transitions. Compress output.

Completion Criteria

Max Response Length

2560 tokens.

Component Architecture / Decision Trees

Architecture Options

| Approach | Trade-off | When to Use |

|----------|-----------|-------------|

| LitElement | Full API (render, styles, lifecycle) | Most components |

| ReactiveElement | No template system, minimal | When bundle is critical |

| @lit-labs/ssr | Server rendering + hydration | SSR-required projects |

| @lit/react | React wrapper generation | React design systems |

Base Class Decision

Do you need the full LitElement API (render, styles, lifecycle)?
  Yes -> LitElement (default)
  No -> Is bundle size critical?
    Yes -> ReactiveElement (no template system, manual DOM management)
    No -> LitElement for maintainability

Do you need SSR?
  Yes -> LitElement + @lit-labs/ssr
  No -> LitElement (default)

Reactive Property Configuration

Is the property part of the public API?
  Yes -> @property() — exposes as HTML attribute, triggers update
  No -> @state() — internal only, triggers update but no attribute

How should the attribute be named?
  CamelCase property -> 'my-prop' attribute (auto kebab-case)
  Need custom name -> attribute: 'custom-name'
  No attribute needed -> attribute: false

Should the attribute reflect changes back to DOM?
  Yes -> reflect: true (useful for CSS attribute selectors)
  No -> reflect: false (default, better performance)

Styling Strategy

How should styles be scoped?
  Shadow DOM -> static styles in LitElement (default, best encapsulation)
  Light DOM -> override createRenderRoot() for shared styles
  Adopted stylesheets -> adoptedStyleSheets for performance (multiple instances)
  CSS custom properties -> ::part() for component customization API

Component Design Patterns

Basic Component with Properties

import { LitElement, html, css } from 'lit'
import { property, state } from 'lit/decorators.js'

export class MyCounter extends LitElement {
  static styles = css`
    :host { display: block; padding: 1rem; }
    button { cursor: pointer; }
  `

  @property({ type: Number }) initial = 0
  @state() private count = 0

  connectedCallback() {
    super.connectedCallback()
    this.count = this.initial
  }

  render() {
    return html`
      <p>Count: ${this.count}</p>
      <button @click=${() => this.count++}>+</button>
      <button @click=${() => this.count--}>-</button>
    `
  }
}

Component with Typed Events

import { LitElement, html } from 'lit'
import { property } from 'lit/decorators.js'

export class MyDropdown extends LitElement {
  @property({ type: Array }) options: string[] = []
  @property({ type: String }) value = ''

  private select(option: string) {
    this.value = option
    this.dispatchEvent(new CustomEvent('select', {
      detail: option,
      bubbles: true,
      composed: true,
    }))
  }

  render() {
    return html`
      <div @click=${(e: Event) => {
        const target = e.target as HTMLElement
        if (target.dataset.value) this.select(target.dataset.value)
      }}>
        ${this.options.map(o => html`
          <div data-value=${o} class=${o === this.value ? 'active' : ''}>
            ${o}
          </div>
        `)}
      </div>
    `
  }
}

Renderless Controller Pattern

import { ReactiveController, ReactiveControllerHost } from 'lit'

export class ResizeController implements ReactiveController {
  private entries: ResizeObserverEntry[] = []
  private observer: ResizeObserver | null = null

  constructor(private host: ReactiveControllerHost) {
    this.host.addController(this)
  }

  hostConnected() {
    this.observer = new ResizeObserver(entries => {
      this.entries = entries
      this.host.requestUpdate()
    })
    this.observer.observe(this.host as HTMLElement)
  }

  hostDisconnected() {
    this.observer?.disconnect()
  }
}

State Management Patterns

Local State with @state

@state() private visible = false
@state() private items: Item[] = []

Derived State via Getter

get total() { return this.items.reduce((s, i) => s + i.price, 0) }
get count() { return this.items.length }

Reactive Controller for Shared Logic

Controllers encapsulate stateful behavior (resize observers, intersection observers, form state) and can be reused across components.

Performance Optimization

Rendering Performance

Bundle Size

Optimization Techniques

Build & Bundle Considerations

Testing Strategies

Unit Testing with Web Test Runner

import { fixture, assert } from '@open-wc/testing'
import './my-element.js'

describe('MyElement', () => {
  it('renders with default properties', async () => {
    const el = await fixture('<my-element></my-element>')
    assert.equal(el.shadowRoot?.querySelector('button')?.textContent?.trim(), 'Click me')
  })

  it('reacts to property changes', async () => {
    const el = await fixture<MyElement>('<my-element></my-element>')
    el.count = 5
    await el.updateComplete
    assert.include(el.shadowRoot?.textContent ?? '', '5')
  })
})

Event Testing

it('dispatches custom event on button click', async () => {
  const el = await fixture<MyElement>('<my-element></my-element>')
  const handler = sinon.spy()
  el.addEventListener('my-event', handler)
  el.shadowRoot?.querySelector('button')?.click()
  assert.isTrue(handler.calledOnce)
  assert.equal(handler.firstCall.args[0].detail, 'clicked')
})

Key Testing Practices

Migration Patterns

From Vanilla Custom Elements to Lit

| Vanilla | Lit |

|---------|-----|

| class MyEl extends HTMLElement | class MyEl extends LitElement |

| observedAttributes() | @property() decorator |

| attributeChangedCallback() | willUpdate() / updated() |

| connectedCallback() + manual render | render() auto-called |

| this.innerHTML = template | return html\...\`` |

| Manual style attachment | static styles = css\...\`` |

Migration order: 1) Change extends to LitElement, 2) Replace observedAttributes with @property, 3) Replace innerHTML with render(), 4) Add static styles, 5) Convert lifecycle methods.

From React to Lit

| React Concept | Lit Equivalent |

|---------------|----------------|

| useState | @state() property |

| useEffect | updated() / willUpdate() |

| useMemo | shouldUpdate() for control |

| JSX | html tagged template literal |

| Props | @property() decorator |

| Event callbacks | CustomEvent dispatch |

Anti-Patterns

  1. Forgetting to call super on lifecycle: super.connectedCallback(), super.disconnectedCallback(), super.updated().
  2. Imperative DOM manipulation in render(): render() should be pure — side effects go in updated().
  3. Large template literals: Break templates into helper functions or sub-components.
  4. Missing @state for internal state: Using @property for internal state exposes it as an HTML attribute.
  5. Events without composed: true: Events can't cross shadow DOM boundaries without composed: true.
  6. Not using lit-html directives: Directives (repeat, classMap, styleMap) optimize rendering vs manual DOM.
  7. Memory leaks from missing disconnectedCallback: Always clean up timers, observers, and event listeners.
  8. Shadow DOM a11y issues: ARIA attributes on host may not cross shadow boundary without :host.

Common Pitfalls

  1. Forgetting to call super on lifecycle — always call super.connectedCallback().
  2. Missing @state for internal state — @property exposes it as HTML attribute.
  3. Events without composed: true — can't cross shadow boundaries.
  4. Large template literals — break into smaller functions.
  5. Memory leaks — always clean up in disconnectedCallback.

Compared With

| Aspect | Lit | Stencil | Vanilla WC |

|--------|------|---------|------------|

| Bundle size | ~5KB | ~8KB | 0KB |

| Rendering | lit-html (template literal) | JSX (compiled) | Manual |

| Reactivity | @property/@state decorators | @Prop/@State decorators | attributeChangedCallback |

| SSR | @lit-labs/ssr | @stencil/core (SSR) | Manual |

| TypeScript | Full support | Required | Optional |

Template Directives Reference

| Directive | Purpose |

|-----------|---------|

| ifDefined | Render attr only if defined |

| classMap | Toggle CSS classes |

| styleMap | Inline styles |

| repeat | Keyed list rendering |

| when | Conditional rendering |

| until | Promise placeholder |

| live | Attribute always matches live value |

| keyed | Force DOM reuse |

| guard | Memoize template parts |

| cache | Cache DOM across conditionals |

Lifecycle Reference

| Method | Purpose |

|--------|---------|

| connectedCallback() | Element added to DOM |

| disconnectedCallback() | Element removed from DOM |

| willUpdate(changed) | Before render |

| update(changed) | Before render (read prop values) |

| render() | Return lit-html template |

| updated(changed) | After render |

| firstUpdated(changed) | First render only |

| shouldUpdate(changed) | Control whether render fires |

Tooling

  1. Lit VS Code Extension — syntax highlighting
  2. @lit/reactive-element — base class without template
  3. @lit-labs/ssr — server-side rendering
  4. @lit/react — React wrapper generation
  5. @lit/localize — i18n
  6. lit-analyzer — type checking
  7. @open-wc/testing — testing utilities
  8. @web/test-runner — test runner
  9. Storybook for Lit — component development

Ecosystem

UI Libraries Built with Lit

Integration Patterns

Rules

References

Handoff

No artifact produced.

Next skill: frontend-universal-web-components for vanilla custom elements and cross-framework compatibility.

Carry forward: LitElement patterns, reactive property config, shadow DOM conventions.

Architecture Decision Trees

Component Design Decision Tree

Does component render dynamic content from properties?
  ├── No  → Pure template with static styles
  └── Yes → Are properties primitive values?
       ├── Yes → @property() with type converter
       └── No  → @property() with custom converter or @state()
            Does the component need to render children/slots?
            ├── Yes → Use <slot> elements in shadow DOM
            └── No  → Closed shadow DOM for encapsulated components

Reactive Strategy Decision Tree

Does the component need to react to external state?
  ├── No  → Static component, no reactive updates needed
  └── Yes → Is the state from DOM events?
       ├── Yes → @eventOptions + this.requestUpdate()
       └── No  → Is the state coming from an observable?
            ├── Yes → Use LitElement + rxjs with connect() pattern
            └── No  → Use @property decorators + willUpdate lifecycle
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.