UI Widget Framework Guide (MVP Architecture)
Adhere strictly to the Model-View-Presenter (MVP) architecture.
- Models (
front_end/models/): Handle business logic and application state. MUST NOT have knowledge of the UI. - Presenters (
Widget): Orchestrate data flow, manage UI-specific state, and handle interactions. - Views (
function): Purely presentational. Stateless functions that receive data/callbacks and render usinglit-html.
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
- Location: Co-located in the same file as its View.
- MUST extend a base
UI.Widgetclass (e.g.,UI.Widget.Widget). Note thatUI.Widget.Widgetis not anHTMLElementand must be appended via.show()orUI.Widget.widget - Constructor MUST assign the injected view function to a private
#viewfield. - Constructor MUST call
super(). If takingelement?: HTMLElement, pass it tosuper(element).super(true)is forbidden. Do not passclassesorjsloginWidgetOptions(super(..., {classes: [...], jslog: ...})); instead, pass container CSS classes andjslogvia the third parameter ofrender(template, target, {container: {classes: [...], attributes: {jslog: ...}}})in the view function (and if the widget uses shadow DOM, passuseShadowDom: 'pure'and extendWidget<ShadowRoot>/VBox<ShadowRoot>withtarget: HTMLElement|DocumentFragmentsorender()appliescontainer.classesandcontainer.attributesto the shadow hostthis.element). - Light DOM vs.
useShadowDom: 'pure': Light DOM (super(element)) is the default. UseuseShadowDom: 'pure'(Widget<ShadowRoot>/VBox<ShadowRoot>) only when<slot>projection is needed or an inline<style>tag pollutes ancestor.textContentassertions in tests (axe_core_test_runner.jsalready normalizesShadowRoottoelement.host). Note that on legacyuseShadowDom: truewidgets,this.contentElementis an inner<div class="widget">inside the shadow root rather than the hostthis.element, whereasuseShadowDom: 'pure'setsthis.contentElementto theShadowRootitself (ui/lit/render.tsappliescontaineroptions toshadowRoot.host). - Multi-branch
containeroptions: Views with multiplerender()branches that pass{container: {classes, attributes}}MUST pass identicalcontaineroptions on everyrender()branch, because omitting them strips previously appliedclassesandattributes(such asjslog) on branch switches. - Dual-overload
Widget<ShadowRoot>promotion: When keeping a legacy positional constructor alongside(element?: HTMLElement, view?: View), placeconstructor(element?: HTMLElement, view?: View);last before the implementation signature and typeView's target asHTMLElement|ShadowRootsoConstructorParametersandViewFunctionHelpers(strictFunctionTypes) resolve cleanly. - Dependencies from
UniverseSHOULD be requested via staticINJECT:static override readonly INJECT = [...] as const;and received as constructor parameter #2 ([dep1, dep2]: UI.Widget.WidgetDependencies<typeof MyWidget>). - Styling MUST be handled within the View.
this.registerRequiredCSS()is forbidden. - Initial render MUST be triggered in
override wasShown(): voidby callingthis.requestUpdate(). External model, workspace, and setting subscriptions SHOULD be attached inwasShown()and detached symmetrically inwillHide(), reconciling incremental state changes that occurred while hidden rather than unconditionally callingreset()and wiping populated presenter state (such as open tree folders or selection) on every re-show. #needsUpdateguard acrossdetach()/ re-show: When a widget flushesperformUpdate()in a legacy positional constructor or can have updates queued beforedetach()cancels them, guardwasShown()with#needsUpdate = true(setthis.#needsUpdate = truebeforethis.requestUpdate()in setters, clearthis.#needsUpdate = falseinperformUpdate(), and checkif (this.#needsUpdate) { this.requestUpdate(); }inwasShown()) instead of#hasRendered = false(which drops updates cancelled bydetach()).- Notifying manual-layout parents after dynamic child removal (
wasHidden()): Most widgets do not need manual parent resize notifications. When a dynamically dismissed child widget (such asInfobar) sits inside a manual-layout parent that requiresthis.parentWidget()?.doResize()after the child leaves the DOM, hookoverride wasHidden()rather thandispose()oroverride onDetach()(dispose()runs while<devtools-widget>is still connected, and<devtools-widget>disconnect skipsonDetach()). - MUST hold all UI state as private class fields (e.g.,
#counter). - To schedule a UI update, MUST call
this.requestUpdate()asynchronously across all presenter methods, property setters, and event handlers.performUpdate()MUST NOT be called directly (except inUI.Dialog.Dialog/UI.GlassPane.GlassPanewrappers whererequestUpdate()is unavailable because they wrap an internal#widgetinstead of extendingWidget—noteUI.Panel.PanelextendsVBox->Widgetand does inheritrequestUpdate(), as doesUI.Dialog.DialogWidget—or when synchronous layout measurement is documented as strictly required). Presenter and presenter-node classes MUST NOT expose imperative view-refresh methods (e.g.,updateTrailingIcons(),updateIcon()); all visual output should be derived declaratively in the view function. - Never call
this.requestUpdate()reentrantly insideperformUpdate(): Doing so triggersUpdateState.INTERRUPTED, aborts the active update controller, and queues a redundant animation frame. Callthis.requestUpdate()at top-level event and action entrypoints instead of inside helpers called duringperformUpdate(). - Blink
web_tests& synchronousperformUpdate()exceptions: Never callthis.performUpdate()synchronously as a workaround for legacy Blinkweb_tests(update those web tests toawait UI.Widget.Widget.allUpdatesCompleteinstead). Synchronousthis.performUpdate()is justified only when: (1) a caller immediately invokes.focus()on a child right after unhiding its container, or (2)PopoverHelper, tooltip bounds, or a legacy positional caller measures layout synchronously beforerequestAnimationFrame(including undersinon.useFakeTimers()whereclock.restore()runs before the next frame).
View (`function`) Rules
- MUST be a pure function, typically named
DEFAULT_VIEW, in the same file as the Presenter. - MUST use the signature:
(input: ViewInput, output: ViewOutput, target: HTMLElement): void(ESLint'sisViewFunctionrequires 3 identifier parameters ending withinput,output, andtarget/element/container, returningvoidorPromise<void>or omitting the return annotation). input: Data and event handlers from the Presenter.output: Callbacks for imperative actions (e.g., focus) provided to the Presenter. If unused,@devtools/no-empty-view-outputrequires typing theoutputparameter asundefined(never{},object,Record<string, never>, or an emptyViewOutputinterface) in the view's signature, andundefinedshould be passed from the presenter.target: The HTML element (orShadowRoot/DocumentFragment) to render into.- The
inputparameter MUST NOT be destructured. Always useinput.propertyName. - Responsibility: Render a
lit-htmltemplate intotarget. - Template Formatting & Whitespace: The custom
htmltag fromui/lit/lit.js(front_end/ui/lit/strip-whitespace.ts) automatically strips\n\s*outside of<...>tags at runtime, so multi-line formatting between text interpolations and inline elements (<span>, etc.) does not introduce whitespace text nodes. - Event & callback contracts: Unpack DOM events (
event.preventDefault(),(e.target as HTMLInputElement).checked,e.detail) and construct/show context menus (const contextMenu = new UI.ContextMenu.ContextMenu(event); input.onContextMenu(item, contextMenu); void contextMenu.show();) insideDEFAULT_VIEWrather than forwarding DOMEventobjects to the presenter. Pass domainItemobjects in callbacks (onSelect: (item: Item) => void), never array indices that go stale across concurrent rebuilds. Becauseui/lit/render.tspasses nohostoption to Lit,@event=${fn}bindings require arrow functions or.bind(this)(Lit swaps the stored callback on re-render without re-registering DOM listeners). - MUST NOT hold state, fetch data, or perform business logic.
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
- To render a child widget, the parent's View MUST use the lit-html directive
UI.Widget.widget. - Prefer
${widget(WidgetClass, {params})}directly as a child expression over<devtools-widget ${widget(WidgetClass, {params})}></devtools-widget>. Never double-wrap<devtools-widget>${widget(WidgetClass, {params})}</devtools-widget>, becausewidget()as a child expression already renders<devtools-widget>. Only use an explicit<devtools-widget>tag when you need to set other HTML attributes/classes, apply additional directives (such aswidgetReforref), or provide child nodes. - Strongly prefer the two-argument
widget(WidgetClass, {params})form over the single-argument factory callbackwidget(element => new WidgetClass(element, ...)). The two-argument form automatically updates properties and callsrequestUpdate()on subsequent renders, whereas a factory callback only runs once on initial instantiation. - If a child widget currently exposes imperative setter methods (e.g.,
setStorageKey(key)orsetStorageBucket(bucket)) instead of public properties/setters, convert them into standard TypeScript setters (set storageKey(key),set storageBucket(bucket)) on the child widget so it can be instantiated and updated declaratively via the two-argumentwidget(WidgetClass, {params})directive. Setter implementations should short-circuit when the value is unchanged and callthis.requestUpdate(). - Configuration is passed via the parameters.
- Properties passed from a parent MUST be declared as public fields or setters on the child presenter class.
- The framework automatically updates these properties and calls
requestUpdate()on the child when the parent re-renders. - Memoize
widget()reference props:WidgetDirectivecompares eachwidgetParamsentry with strict!==and callschild.requestUpdate()whenever any reference changes. Memoize object, array,Set, and callback props instead of allocating fresh literals or.bind(this)closures inperformUpdate(). - Avoid
UI.Widget.WrapperWidget: Do NOT passUI.Widgetinstances (such asnew ChildWidget(),UI.TabbedPane.TabbedPane/tabbedLocation.tabbedPane(),StackLocation.widget(),UI.ListWidget.ListWidget, orUI.SplitWidget.SplitWidget) viaViewInputto wrap inUI.Widget.WrapperWidget. - Child widgets: Refactor the child widget to accept
element?: HTMLElementin its constructor and setters for its state, and instantiate it declaratively in the view with${widget(ChildWidget, {...})}. TabbedPaneandStackLocation: Create tabbed panes and stack panes declaratively in the view using<devtools-tabbed-pane>(or${widget(UI.TabbedPane.TabbedPane, ...)}) and<devtools-stack-pane>rather than passing aTabbedPaneorStackLocation.widget()instance throughViewInputtoWrapperWidget.UI.ListWidget.ListWidgetandUI.ListWidget.Delegate: Do NOT keepthis.listandUI.ListWidget.Delegateon the presenter (callingthis.list.clear(),this.list.appendItem(),this.list.addNewItem(), renderingrenderItem/beginEditinto aDocumentFragment, and mountingthis.listviaWrapperWidget). ReplaceListWidget+ListWidget.Delegatewith<devtools-list>(ui/components/lists/lists.js) driven by pureViewInputdata and callbacks (using<devtools-prompt>, an inline editor row, orUI.Dialog.Dialogfor editing). If legacyListWidget.EditorDOM/screenshot goldens must be preserved temporarily in an incremental CL, moveListWidget+ListWidget.Delegateownership into the view layer (e.g. a small view-layer child class extendingUI.ListWidget.ListWidgetdirectly and instantiated via${widget(...)}inDEFAULT_VIEW, withoutWrapperWidget) so the presenter only passes pure data and callbacks inViewInput.WrapperWidgetis only justified when reparenting a shared stateful singleton across multiple containers (such asConsoleView.instance()orSourcesView) or bridging an opaqueUI.Widgetreturned by an external factory. Remember thatWrapperWidgetsetsdisplay: contentson its<devtools-widget>host element, so never put sizing, border, or background classes on that<devtools-widget>host (wrap it in a<div>instead).- External imperative DOM hosts &
widgetCounterMap:Node.prototype.appendChild,insertBefore,removeChild, andremoveChildrenthrow on widget elements, andmarkAsExternallyManaged()under-counts ancestorwidgetCounterMapondetach()(#showWidgetskips incrementing whiledetach()still decrements). When mounting a widget into external imperative DOM (such as CodeMirror panels), callwidget.show(container, undefined, true)after the external host connectscontainerto the DOM, paired withwidget.detach()beforecontaineris removed. SwatchPopoverHelpertriggers: Bind@mousedown=${(e: Event) => e.consume()}on the trigger element soSwatchPopoverHelper's documentmousedownlistener does not close the popover beforeclickfires, andawait child.updateComplete(obtained viawidgetRef) beforeSwatchPopoverHelper.show().- Non-widget render adapters: For CodeMirror
WidgetType.toDOM()orListWidget.Delegate.renderItem(), render a 3-parameter view(input, _output: undefined, target: DocumentFragment): voidintodocument.createDocumentFragment()and returnfragment.firstElementChild. ForUI.Toolbar.Provideritems that do not need a fullWidget, pass a real element tonew UI.Toolbar.ToolbarItem(document.createElement('button'))and callrender(tpl, toolbarItem.element, {container: {classes, attributes, listeners}})directly (never render into aDocumentFragmentand reparentfragment.firstElementChild, which detaches Lit'sChildPartmarkers), or return<devtools-button>templates fromtoolbarItems(). - Listening to Child Widget Events (
eventMixin): When a childUI.WidgetusesCommon.ObjectWrapper.eventMixin(UI.Widget.Widget), callingthis.dispatchEventToListeners(Events.FOO, payload)also dispatches a non-bubblingnew CustomEvent(Events.FOO, {detail: payload})on the widget's host<devtools-widget>element. Parent Lit templates can listen declaratively with<devtools-widget ${widget(ChildWidget, {...})} @Foo=${(e: CustomEvent<Payload>) => input.onFoo(e.detail)}></devtools-widget>(Lit preserves the case of@Foofrom the template string). This only works on the<devtools-widget>element itself (theCustomEventdoes not bubble) and only forUI.Widgetclasses usingeventMixin(plainObjectWrappersubclasses do not havedispatchDOMEvent).
Refactoring Legacy Components
When migrating imperative components (extending UI.Widget.VBox, UI.Panel.Panel, or HTMLElement) to the MVP architecture:
- Analyze Rendering Logic: Identify where DOM is created (constructor,
wasShown, imperative methods). This logic moves to theDEFAULT_VIEW. - Convert Base Class:
- Prefer extending
UI.Widget.Widget(orUI.Panel.Panelfor panels, which extendsVBox->Widgetand does inheritrequestUpdate()). - Special Case:
UI.Dialog.DialogandUI.GlassPane.GlassPanewrap an internal#widgetinstead of extendingWidget, so render intothis.contentElementdirectly via a view function (or composeUI.Dialog.DialogWidgetdeclaratively via `${widget(UI.Dialog.DialogWidget, {open, content: html...})}` in a parent view rather than subclassing it).
- State Migration: Move DOM-stored state to
#privateclass fields and schedule updates viathis.requestUpdate(). - Update Usage: Replace
new MyComponent()instantiations with declarative${widget(MyComponent, {params})}in parent templates. - Scoping Styles: Ensure your CSS file uses an
@scope to (devtools-widget > *)block to prevent style leaks. Land@scopeCSS 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:
@devtools/no-unscoped-light-dom-styles(ESLint): checks stylesheets injected by Light DOM widgets (<style>${styles}</style>,this.registerRequiredCSS(),appendStyle()) and requires all rules to sit inside a top-level@scopeblock. Never add new files to the self-cleaningburndownlist ineslint.config.mjs; remove migrated files from the list once scoped.plugin/check_scope_selectors(stylelint): unconditionally forbids:hostinside@scope(even with:scopeor&), and flags ancestor selectors that receive an implicit:scopedescendant combinator and cannot match without:scopeor&(:host-context(),:root,html,body,.theme-with-dark-background,.platform-*,.overlay-scrollbar-enabled).
Key @scope Gotchas & Rules:
:scopeinstead of:host::hostis Shadow DOM-only and never matches inside@scope. Style the widget's root container element with:scope.- Theme-aware tokens instead of theme or platform classes: Because un-anchored selectors inside
@scopereceive an implicit:scopeprefix, selectors like.theme-with-dark-background .fooor:host-context(...)look inside the widget for the ancestor class and never match. Use theme-aware design tokens (--sys-color-*/--app-color-*) instead. - Shared stylesheets: Do not inject
inspectorCommonStylesortextButtonStylesinto Light DOM views (installComponentRootStyles()already injects them globally into the document and shadow roots). When a.cssfile (with no:host,:root, or ancestor theme selectors) is shared only between Light DOM anduseShadowDom/useShadowDom: 'pure'widgets, wrap the.cssfile directly in@scope to (devtools-widget > *)(:scopematches the shadow host inuseShadowDom: 'pure') and import./Foo.css.jsdirectly rather than via a namespace import (Foo.barStyles), preserving CSS hot reload. Wrap other shared stylesheets inline as<style>@scope to (devtools-widget > *) { ${styles} }</style>so Shadow DOM consumers stay unaffected. - Lower boundary and imperative child widgets: The
(devtools-widget > *)lower boundary stops cascading into declarative<devtools-widget>children (${widget(...)}), but it does not stop at legacy imperatively attached<div class="widget">children (childWidget.show(container)). - Small, Standalone CLs: Always land
@scopeCSS wrapping in a dedicated, standalone CL separate from logic, template, or widget-promotion CLs so visual regressions are easy to bisect.
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
- Raw Elements: Use
Directives.ref(fromui/lit/lit.js) to obtain a reference to a rawHTMLElementonly when strictly required for legacy imperative APIs (e.g.,splitWidget.installResizer(element)). When a shared DevTools UI primitive (ui/kit,ui/components,ui/legacy) would force callers to useref(...)+ imperative setters just to link elements together (such as a<devtools-menu>trigger anchor), extend the shared primitive with an HTML-native ID/attribute API in a standalone prerequisite CL rather than addingref(...)boilerplate at call sites. - Child Widgets: Use
UI.Widget.widgetRefto obtain the class instance of a child widget inside the view function if you need to call imperative methods on it. Do NOT store child widget instances onViewOutputas a final result (doing so is only acceptable temporarily in intermediate migration CLs). Instead, either supply all needed configuration declaratively through setters/inputs on the child widget, or if imperative calls are strictly necessary, expose narrow action functions onViewOutput(e.g.,output.doLayout = () => splitWidget.doLayout(),output.revealPosition = pos => childWidget.revealPosition(pos)). Do not keepget*ForTest()methods that return child widget instances viaViewOutput; tests should query rendered<devtools-widget>elements via.getWidget()or assert onViewInputviacreateViewFunctionStub. Do preserve existing live presenter notification hooks (such asupdatedForTest()) at their original call points when legacy Blinkweb_testsawait them viaTestRunner.addSniffer.
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; }).
UI.Toolbar.ProviderWidgets (new ToolbarItem(this.element)):Widget.#showWidget()unconditionally removes'hidden'fromthis.elementwhenToolbar.appendToolbarItem(orshow()) mounts the widget. AnyUI.Widgetwrappingthis.elementinUI.Toolbar.ToolbarItemthat can start hidden must re-applythis.#toolbarItem.setVisible(...)inoverride show(...)andoverride wasShown(), with a unit test mounting the widget into a<devtools-toolbar>while initially hidden.
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
- Leaf
ref()text helpers &<canvas>: Never attach atextContent-mutatingref()helper (setTextContentTruncatedIfNeeded,highlightRangesWithStyleClass) to an element that also contains${...}ChildPartexpressions (mutatingtextContentremoves Lit'sChildPartmarkers and throws on re-render); isolate it on an empty leaf<span ${ref(...)}></span>. In<canvas ${ref(el => ...)}>, always callctx.clearRect(0, 0, el.width, el.height)beforectx.drawImage(...)because inlinerefclosures re-run on every render. ifDefined&styleMap: Destructureconst {ifDefined} = Directives;(lit-analyzerrejectsDirectives.ifDefined(...)on string attributes), and useDirectives.styleMap({...})for dynamic inline styles instead of interpolatedstyle="..."strings.<devtools-data-grid>: KeyDirectives.repeatby data item identity (item => item) rather than array index whenever cells contain${widget(...)}, becauseDataGridElementclones<td>cells withcloneNode(true)and misses in-place widget updates unless the<tr>is replaced.<devtools-button>,<devtools-checkbox>, &<devtools-icon>: On<devtools-button>, place.iconName=${...}before.variant=${...}(set variantrenders immediately and throws ificonNameis unset forICON/TOOLBARvariants) and bind.title=${...}as a JS property rather thantitle=${...}so dynamic updates re-render the inner<button>. On<devtools-checkbox>, preservetitle=${title}alongside${UI.UIUtils.bindToSetting(setting)}(when migratingCheckboxLabelorSettingsUI.SettingsUI.createSettingCheckbox) for[title="..."]E2E selectors; raw<input type="checkbox">elements are banned in Lit templates by@devtools/no-raw-checkbox-input. For<devtools-icon>, keep a side-effectimport '../../ui/kit/kit.js';(and../../ui/kit:bundleinBUILD.gn) so the custom element registers in isolated tests.
`<devtools-tree>` & Editable `<devtools-prompt ?editing>` Rows
- Keep
<devtools-tree>(ui/legacy/legacy.js) contracts intact without wideningfront_end/ui/legacy/Treeoutline.ts(TreeViewElement/TreeViewTreeElement). Drive selection and expansion purely via?selected,?open,@select, and@expand. Guard@selecthandlers withBoolean(e.detail?.selectedByUser)when presenter selection is already set, becauseTreeViewElement.focus()selects the first child withselectedByUser: false. - Keep
<devtools-prompt ?editing>persistently mounted in the DOM and toggle?editingdeclaratively; do not duplicatearia-labelon inner prompts when the<li role="treeitem">already labels the row. PairUI.UIUtils.markBeingEdited(container, true)andUI.UIUtils.markBeingEdited(container, false)soUI.UIUtils.isBeingEditedsuppresses focus theft. - Child widget isolation for editable tree rows: Because
<devtools-tree>clones light DOM into shadow DOM and re-clones an<li role="treeitem">whenever any descendant attribute mutates, place editable prompts inside a small childUI.Widget(${widget(RowPromptWidget, {...})}) so toggling?editingupdates the child widget in place without triggering a tree re-clone and blurring the active input. - Custom elements inside
<devtools-tree>templates whose state is passed via JS properties (.data) must overridecloneNode(deep)to copy.dataand reflect dynamic state via DOM attributes so shadow clones update reliably. Place reflective attributes such asdata-badge=${badge}on an inner<span>(never on<li role="treeitem">, whereTreeViewElement.updateNodereturns early without callingrefreshSoon()), and style.tree-outline li > .tree-element-titlewithdisplay: flex; align-items: center; width: 100%so custom icons/spans do not wrap and clip.
Dependencies
- View Dependencies: The
DEFAULT_VIEWis typically a module-level function. Ensure all dependencies (enums, constants, other components) are imported at the top of the file so they are available in the function scope. - Presenter (
Universe) Dependencies: To access dependencies managed byUniverse(e.g.SDK.TargetManager.TargetManager,Common.Settings.Settings), declare a staticINJECTarray on theWidgetsubclass:
```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.
describe+ modular hooks /TestUniverse: Use plaindescribe(from'mocha') with modular setup hooks (setupLocaleHooks(),setupSettingsHooks(),setupRuntimeHooks()) andTestUniverse(seefoundation-test-migration). Do not usedescribeWithEnvironmentordescribeWithMockConnectionin new or migrated unit tests. For direct presenter tests (new MyWidget(...)withcreateViewFunctionStub) on widgets declaringINJECT, instantiateconst universe = new TestUniverse();and pass[universe.targetManager, ...]as constructor argument #2 (new MyWidget(...)runs beforerenderElementIntoDOM(widget)callswidget.show(container), sosetTestUniverseForWidgetsdoes not populateINJECTconstructor parameters there). For widgets mounted declaratively via thewidget(...)directive,renderElementIntoDOMsupplies a defaultTestUniverseautomatically viaUniverseRequestEvent(overridable withsetTestUniverseForWidgets).createViewFunctionStub: Stubs the view to captureinputdata.renderElementIntoDOM: Marks the widget as root and attaches it to the DOM to trigger lifecycle methods (likewasShown).view.nextInput: A promise that resolves with the nextinputwhen the widget re-renders.- Simulating Events: Invoke callbacks directly (e.g.,
view.input.onButtonClick()), do not interact with the DOM.
// 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.