Ui widgets

From ChromeDevTools/devtools-frontend · View interactive version

Ui widgets is an AI agent skill from the GitHub repository ChromeDevTools/devtools-frontend. Guidelines for building UI widgets using the MVP architecture in DevTools. Covers Widget lifecycle, lit-html views, and state management.

How to use this skill

Skill file

UI Widget Framework Guide (MVP Architecture)

Adhere strictly to the Model-View-Presenter (MVP) architecture.

Refactoring Note: When refactoring legacy widgets to this framework, the widget's class name MUST NOT be changed. Truly reusable UI primitives (front_end/ui/components/**, front_end/ui/kit/**) stay custom elements (HTMLElement) and should not be migrated to DEFAULT_VIEW or UI.Widget, whereas single-use custom elements under front_end/panels/**/components/ used solely for encapsulation in one feature should migrate to UI.Widget with @scope to (devtools-widget > *) styles.

Presenter (`Widget`) Rules

View (`function`) Rules

Helper Functions in Views vs. Child Widgets

Complex views and repeated item rows should be broken down using pure helper functions returning LitTemplate inside DEFAULT_VIEW (iterating over pure data arrays on input), rather than extracting stateless single-row or single-item child UI.Widget subclasses. Only extract a child UI.Widget when the sub-component owns independent lifecycle (wasShown/willHide), external subscriptions, or an isolated DOM mutation boundary (such as editable <devtools-prompt> rows inside <devtools-tree>).

// clang-format off
const DEFAULT_VIEW = (input: ViewInput, _output: undefined, target: HTMLElement): void => {
  const renderHeader = (): LitTemplate => {
    return html`<h1>${input.title}</h1>`;
  };
  // ...
  render(html`
    <div class="child-widget">
      ${renderHeader()}
    </div>
  `, target);
};
// clang-format on

Composition

Refactoring Legacy Components

When migrating imperative components (extending UI.Widget.VBox, UI.Panel.Panel, or HTMLElement) to the MVP architecture:

  1. Analyze Rendering Logic: Identify where DOM is created (constructor, wasShown, imperative methods). This logic moves to the DEFAULT_VIEW.
  2. Convert Base Class:
  1. State Migration: Move DOM-stored state to #private class fields and schedule updates via this.requestUpdate().
  2. Update Usage: Replace new MyComponent() instantiations with declarative ${widget(MyComponent, {params})} in parent templates.
  3. Scoping Styles: Ensure your CSS file uses an @scope to (devtools-widget > *) block to prevent style leaks. Land @scope CSS wrapping in its own small, standalone CL separate from widget migration CLs so visual regressions are easy to bisect:

```css

@scope to (devtools-widget > *) {

...

}

```

Key Implementation Details (Gotchas)

Styling Strategy

DevTools widgets typically render into Light DOM (the default for UI.Widget). To ensure styles are scoped to the component and do not leak into child widgets, wrap your CSS in an @scope block:

/* myWidget.css */
@scope to (devtools-widget > *) {
  :scope {
    display: flex;
  }
  .my-class { ... }
}

Then, include the styles in your DEFAULT_VIEW:

import myWidgetStyles from './myWidget.css.js';
// ...
render(html`
  <style>${myWidgetStyles}</style>
  <div class="my-widget">...</div>
`, target);

Automated Lint Enforcement:

Key @scope Gotchas & Rules:

Note: The {host: input} option in render() is generally not required unless you are using specific Shadow DOM patterns that necessitate it. The @scope strategy is the preferred method for style isolation in DevTools widgets.

Legacy Interop & Refs

Visibility (`?hidden` Attribute Only)

Toggle element visibility declaratively using the HTML ?hidden attribute:

html`<div ?hidden=${!input.isVisible}>...</div>`

Never combine a .hidden CSS class (classMap({hidden: ...}) or classList.toggle('hidden', ...)) with ?hidden (inspectorCommon.css already defines [hidden] { display: none !important; }).

Declarative Default Focus (`autofocus` / `?autofocus`)

UI.Widget.prototype.focus() natively queries [autofocus] via getDefaultFocusedElement() across both plain HTML elements (e.g. <devtools-tree autofocus>) and child widgets. Mark the default focus target with autofocus or ?autofocus=${...} directly in the Lit template (ensuring at most one element has autofocus in any render state) instead of overriding focus(), calling this.setDefaultFocusedElement(...), plumbing focus closures through ViewOutput, or mutating element.autofocus / setAttribute('autofocus', ...) / toggleAttribute('autofocus', ...) imperatively in TypeScript or ref(...) callbacks.

Directives & Built-in Elements

`<devtools-tree>` & Editable `<devtools-prompt ?editing>` Rows

Dependencies

```ts

export class MyWidget extends UI.Widget.Widget {

static override readonly INJECT = [SDK.TargetManager.TargetManager, Common.Settings.Settings] as const;

#targetManager: SDK.TargetManager.TargetManager;

#settings: Common.Settings.Settings;

#view: View;

constructor(

element?: HTMLElement,

[targetManager, settings]: UI.Widget.WidgetDependencies<typeof MyWidget> = [],

view: View = DEFAULT_VIEW,

) {

super(element);

this.#targetManager = targetManager;

this.#settings = settings;

this.#view = view;

}

}

```

instantiateWidget automatically resolves dependencies from Universe via UniverseRequestEvent and passes them as constructor parameter #2. When mounting widgets declaratively via widget(...) inside renderElementIntoDOM, a default TestUniverse answers UniverseRequestEvent automatically (override via setTestUniverseForWidgets); when instantiating new MyWidget(...) directly in presenter unit tests, construct const universe = new TestUniverse(); and pass [universe.targetManager, ...] as constructor parameter #2.

Step-by-Step Implementation Example

1\. Create the Widget File and Styles

Example: front_end/panels/my_example/MyExampleWidget.ts.

/* front_end/panels/my_example/myExampleWidget.css */
@scope to (devtools-widget > *) {
  p {
    color: blue;
  }
}
// front_end/panels/my_example/MyExampleWidget.ts

import * as UI from '../../ui/legacy/legacy.js';
import {html, render} from '../../ui/lit/lit.js';

import myExampleWidgetStyles from './myExampleWidget.css.js';

// 1. Define Input data shape. (Assuming Child Widget configuration for completeness)
export interface ViewInput {
  title: string;
  counter: number;
  onButtonClick: () => void;
}

// 2. Define the View function (output is undefined when no imperative actions exist).
// clang-format off
const DEFAULT_VIEW = (input: ViewInput, _output: undefined, target: HTMLElement): void => {
  render(html`
    <style>${myExampleWidgetStyles}</style>
    <div class="child-widget">
      <h3>${input.title}</h3>
      <p>Counter: ${input.counter}</p>
      <button autofocus @click=${input.onButtonClick}>Increment</button>
    </div>
  `, target);
};
// clang-format on

// 3. Type alias for the view.
type View = typeof DEFAULT_VIEW;

// 4. Define the Presenter.
export class MyExampleWidget extends UI.Widget.Widget {
  #counter: number = 0;

  // Public field REQUIRED to receive data from a parent.
  title: string = 'Default Title';

  #view: View;

  constructor(element?: HTMLElement, view: View = DEFAULT_VIEW) {
    super(element);
    this.#view = view;
  }

  override wasShown(): void {
    super.wasShown();
    // Initial render trigger.
    this.requestUpdate();
  }

  #handleButtonClick = (): void => {
    this.#counter++;
    this.requestUpdate();
  };

  override performUpdate(): void {
    const viewInput = {
      title: this.title,
      counter: this.#counter,
      onButtonClick: this.#handleButtonClick,
    };
    this.#view(viewInput, undefined, this.contentElement);
  }
}

2\. Compose Widgets (Parent Widget)

Example: front_end/panels/parent/ParentWidget.ts. Demonstrates passing state via widgetConfig and a view with no output.

// front_end/panels/parent/ParentWidget.ts

import * as UI from '../../ui/legacy/legacy.js';
import {html, render} from '../../ui/lit/lit.js';
import * as MyExample from '../my_example/my_example.js';

import parentWidgetStyles from './parentWidgetStyles.css.js';

const {widget} = UI.Widget;

interface ViewInput {
  title: string;
  onTitleChange: () => void;
}

// Parent View
// clang-format off
const DEFAULT_VIEW = (input: ViewInput, _output: undefined, target: HTMLElement): void => {
  render(html`
    <style>${parentWidgetStyles}</style>
    <div class="parent-container">
      <h1>Parent Widget</h1>
      <button @click=${input.onTitleChange}>Change Child Title</button>

      <!-- Pass properties to the child widget. -->
      ${widget(MyExample.MyExampleWidget.MyExampleWidget, {title: input.title})}
    </div>
  `, target);
};
// clang-format on

type View = typeof DEFAULT_VIEW;

// Parent Presenter
export class ParentWidget extends UI.Widget.Widget {
  #childTitle: string = 'Initial Title';
  #view: View;

  constructor(element?: HTMLElement, view: View = DEFAULT_VIEW) {
    super(element);
    this.#view = view;
  }

  override wasShown(): void {
    super.wasShown();
    this.requestUpdate();
  }

  #handleChangeTitleClick = (): void => {
    this.#childTitle = `Title set at ${new Date().toLocaleTimeString()}`;
    this.requestUpdate();
  };

  override performUpdate(): void {
    this.#view({
      title: this.#childTitle,
      onTitleChange: this.#handleChangeTitleClick,
    }, undefined, this.contentElement);
  }
}

3\. Testing Widgets

Ship unit tests in the same CL as the presenter/view change (never defer tests to a follow-up test-only CL). Testing focuses on the Presenter's logic using createViewFunctionStub, while template layout is covered by assertScreenshot / E2E tests (per docs/ui_engineering.md). When adding targeted unit tests for view rendering, name the suite describe('view', ...) (never describe('... DEFAULT_VIEW', ...)), and avoid 80–150 line synthetic DEFAULT_VIEW DOM assertion suites that duplicate presenter tests. Note that new MyWidget() defaults this.element to <div class="widget">, so Light DOM stylesheets written with an explicit @scope (devtools-widget) root require new MyWidget(document.createElement('devtools-widget')) (or mounting via ${widget(MyWidget)}) in unit and screenshot tests.

// front_end/panels/my_example/MyExampleWidget.test.ts

import {assert} from 'chai';
import {describe, it} from 'mocha';

import {
  renderElementIntoDOM,
} from '../../testing/DOMHelpers.js';
import {setupLocaleHooks} from '../../testing/LocaleHelpers.js';
import {createViewFunctionStub} from '../../testing/ViewFunctionHelpers.js';

import * as MyExample from './my_example.js';

const {MyExampleWidget} = MyExample.MyExampleWidget;

describe('MyExampleWidget', () => {
  setupLocaleHooks();

  // Helper to set up the widget with a stubbed view.
  async function createWidget() {
    // 1. Stub the view function.
    const view = createViewFunctionStub(MyExampleWidget);

    // 2. Instantiate the widget, injecting the stub.
    const widget = new MyExampleWidget(undefined, view);

    // 3. Render the widget into the DOM (triggers `wasShown`).
    renderElementIntoDOM(widget);

    // 4. Wait for the initial render.
    await view.nextInput;

    return {view, widget};
  }

  it('renders with initial state', async () => {
    const {view} = await createWidget();
    assert.strictEqual(view.input.counter, 0);
  });

  it('increments counter on button click', async () => {
    const {view} = await createWidget();

    // Simulate the click by invoking the callback.
    view.input.onButtonClick();

    // Wait for the re-render.
    const finalInput = await view.nextInput;

    assert.strictEqual(finalInput.counter, 1);
  });

  it('updates its title when a new one is passed in', async () => {
    const {view, widget} = await createWidget();

    widget.title = 'New Test Title';
    widget.requestUpdate();

    const finalInput = await view.nextInput;
    assert.strictEqual(finalInput.title, 'New Test Title');
  });
});

Improving this Guide

This document is a living guide. If you find that the instructions are incomplete, lead to errors, or could be improved, please suggest updates. Your goal is to make this guide as helpful as possible for both human developers and your future AI counterparts.

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.