Subskill: Local Lit-HTML Renderer (Pass 2)
This subskill converts consolidated imperative DOM construction helper methods
into reactive, declarative Lit-html templates, rendering them locally inside the
existing element containers.
1. Declarative Technology Migration
- Conserve Abstraction Topology:
- Maintain the existing class hierarchy, helper class boundaries, and
logical groups.
- Preserve existing standalone/module-level DOM helper functions (e.g.,
linkifyIcon, maybeCreateLinkToElementsPanel) and class helper
methods in their original locations, converting DOM-returning helpers in
place to return LitTemplate (or Promise<LitTemplate|null>) rather
than deleting and inlining them into performUpdate() or DEFAULT_VIEW.
- Update Low-Fanout Shared Helpers Instead of Inlining: When migrating a
caller of a shared cross-module DOM helper (such as
UI.UIUtils.maybeCreateNewBadge) that encapsulates non-trivial markup or
visual logging across a small set of callers, convert the shared helper
to return LitTemplate and update its callers in a standalone
prerequisite CL instead of inlining its markup at each call site.
- Do not aggressively "flatten" classes or collapse helper abstractions
into the main view just to coerce a single master template. Pass 2
should only change the implementation details of rendering (imperative
-> declarative) within existing compartments, not the public API or
responsibilities of objects.
- Determine Render Lifecycle per Layer:
- For UI.Widget classes: Define or update
performUpdate()to execute
the main lit render call, and use this.requestUpdate() to queue
updates.
- For Delegate/Helper classes: Identify the custom update hook (e.g.,
update() or scheduleUpdate()) and invoke render() directly inside
that method. Do not introduce Widget lifecycle methods
(performUpdate) on classes that do not inherit them.
- Import Modern Templating (Named Imports Only):
- Always use named imports from
../../ui/lit/lit.js:
```typescript
import {html, nothing, render, Directives, type LitTemplate} from '../../ui/lit/lit.js';
const {ifDefined, ref, styleMap} = Directives;
```
- NEVER use namespace imports like
import * as Litor reference
Lit.nothing / Lit.render. Named imports enable better tree-shaking and
maintain consistent codebase style.
- Destructure
const {ifDefined} = Directivesfor Attribute Bindings:
lit-analyzer's no-incompatible-type-binding rule only recognizes the
bare identifier ifDefined(value) for string | undefined bindings on
string attributes and rejects Directives.ifDefined(value).
- Use
Directives.styleMap({...})for Dynamic Styles: Never write
interpolated style="width: ${x}px" strings in Lit templates. Bind
`style=${styleMap({width: ${x}px})} (or Directives.styleMap({...})`)
instead.
- Modern Component Mapping:
- MANDATORY: You MUST read and load ui_engineering.md first to understand specific component mappings (e.g., Toolbar vs
devtools-toolbar). Do not assume standard Lit defaults. - If unsure, also consult the automatic migration code
- Replace Imperative Item & Cell Factories with Data Loops: Do not leave
UI.ListDelegate.createElementForItem(UI.SoftDropDown),DataGridNode.createCell(DataGridImpl), orUI.TreeOutlineitem builders in place. Pass a pure data-only items array inViewInputand map over it declaratively inside<button>+<devtools-menu>,<devtools-list>,<devtools-data-grid>, or<devtools-tree>. - Prefer HTML-Native Attributes Over
ref(...)Wiring Setters: Before usingref(...)to wire two elements together or configure a shared DevTools UI primitive imperatively (e.g. menu anchor/origin), check whether the primitive supports or should gain an HTML-native ID/attribute API in a standalone prerequisite CL. Drop host-level workarounds in favor of declarative component attributes.
- Local Modular Renders:
- If the class contains multiple separate legacy container fields (e.g.,
fields generated by appendField or createChild on a parent layout),
prefer local modular renders (rendering templates individually into
each container) to preserve the legacy layout framework. Do not force a
monolithic template if doing so violates the existing topology.
- Resolve TypeScript Type Friction:
- Legacy DevTools elements may be typed as
Element. Lit'srender()
function expects HTMLElement | DocumentFragment.
- When rendering into legacy containers, cast the container using `as
HTMLElement or update its class property type definition from Element`
to HTMLElement to satisfy the TypeScript compiler.
- Example:
render(this.template(), this.containerField as HTMLElement);
- Delegate to Unmigrated Rendering Engines:
- Do not attempt to rewrite complex historical subsystems (like Linkifiers
or specialized UI utilities) to be "pure Lit" during this pass.
- Capitalize on Lit's ability to interpolate standard
HTMLElementorElementinstances directly. Treat unmigrated utilities as "black boxes" that generate DOM, and embed their output in standard template expressions:html<div>${this.legacyElement}</div>``. - CRITICAL: Before treating any component as "unmigrated," you MUST follow steps in Section 4. You are only allowed to use this escape hatch if no declarative migration instructions exist.
- Handle Asynchronous DOM Updates:
- For asynchronous callback-driven updates (e.g., elements updated in a
.then() callback), render the parent container or a placeholder
template first. Once the data is retrieved, execute a local render()
inside the callback targeting the specific sub-container.
- Template Factorization Strategies:
- Prefer
nothing: Use Lit'snothingsentinel instead of empty
strings '' or empty templates for conditional rendering.
- Parameterized Fragment Factories: For repeated UI patterns or
intermediate layout branches, extract them into parameterized helper
functions inside the class scope returning LitTemplate. This avoids
monoliths, preserves readability, and reuses template cache strategies.
- Isolate Text-Mutating
ref()Callbacks on Empty Leaf<span>Elements:
Never attach a ref(...) callback that mutates el.textContent or child
nodes (such as el.setTextContentTruncatedIfNeeded(...) or
UI.UIUtils.highlightRangesWithStyleClass(...)) to an element that also
contains Lit ${...} child expressions. Setting el.textContent
detaches Lit's internal ChildPart comment markers and causes subsequent
in-place updates to throw
TypeError: Cannot read properties of null (reading 'nextSibling').
Isolate imperative text mutations on a dedicated empty leaf
<span ${ref(el => { ... })}></span>.
- Visual Parity, CSS Adaptation, and Accessibility:
- Zero-Tolerance Regression: Screenshot tests are the ground truth for this phase. Any visual diff (above 0%) in the generated screenshots is unacceptable and must be resolved before proceeding.
- CSS Selector Migration: When replacing legacy imperative components/widgets with modern web components (e.g., replacing legacy
DataGridwith<devtools-data-grid>), inspect and update the associated.cssfile. Replace legacy class selectors (.data-grid) with tag selectors (devtools-data-grid). - Strict Tag/Class Parity: Do not change tag types (e.g.,
spanto
div) or drop class names during template translation, as CSS may
depend on them.
- Explicit Component Variants & Accessible Labels: Modern Custom Element (e.g.
<devtools-button>) defaults may not match legacy appearance.
Explicitly bind .data=${{variant: Buttons.Button.Variant.OUTLINED}}
(or .variant=${...}) rather than relying on defaults. On icon-only
<devtools-button> elements, always bind .accessibleLabel=${label}
(setting title or HTML aria-label alone leaves the inner shadow
<button> unnamed under axe-core because <devtools-button> sets
role="presentation" on its host).
- Place
.iconName=${...}BEFORE.variant=${...}: When binding
individual <devtools-button> properties, Button.set variant runs
#render() immediately and throws Error: Icon button requires an icon
(or Toolbar button requires an icon) if .iconName is not yet set.
- Bind Dynamic
.title=${...}as a JS Property:Buttons.Button.Button
overrides set title(title: string) to re-render its inner <button>
without an attributeChangedCallback, so HTML title=${...} leaves
dynamic tooltip and aria-label updates one render behind.
- Accessibility Preservation: Convert custom accessibility
instrumentation (like ARIAUtils.markAsAlert()) to native ARIA
attributes in the template (e.g., role="alert", aria-live="polite").
- Visibility (
?hiddenAttribute Only): Use?hidden=${...}
exclusively to toggle visibility in templates. 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): Mark the
default focused element with autofocus or ?autofocus=${...} directly
in the Lit template instead of collecting elements via ref(...),
plumbing focus callbacks through ViewOutput, or mutating
element.autofocus / setAttribute('autofocus', ...) imperatively in
TypeScript. UI.Widget.prototype.focus() queries [autofocus]
automatically via getDefaultFocusedElement().
<devtools-tree>& Persistent<devtools-prompt ?editing>Patterns:
When rendering <devtools-tree .template=${html<ul role="tree">...</ul>}>:
- Preserve
front_end/ui/legacy/Treeoutline.tscontracts without
widening internal classes or exposing TreeOutline getters on the
presenter.
- Drive selection and expansion declaratively via
?selected,?open,
@select, and @expand.
- Do not duplicate
aria-labelon inner prompts when the enclosing
<li role="treeitem"> already labels the row, do not duplicate
class="tree-element-title" on inner spans (which compounds opacity
rules), and return nothing for trailing icons when none exist.
- Host editable
<devtools-prompt ?editing>rows in a childUI.Widget
(${widget(RowPromptWidget, {...})}) so <devtools-tree>'s
MutationObserver does not re-clone the row and blur the active input.
- Ensure custom elements with state passed via JS properties (
.data)
override cloneNode(deep) and reflect dynamic state via DOM
attributes so shadow clones stay updated.
- Light DOM CSS Encapsulation (
@scope): - Verify stylesheets satisfy
@devtools/no-unscoped-light-dom-styles. Never add files to theburndownlist ineslint.config.mjs; remove the entry fromburndownonce scoped. - Obey
plugin/check_scope_selectors: never use:hostinside@scope(it is unconditionally forbidden, even with:scopeor&), use:scopeto style the root container, and use theme-aware design tokens (--sys-color-*/--app-color-*) instead of ancestor classes like.theme-with-dark-backgroundor:host-context(...)(which receive an implicit:scopeprefix and never match without:scopeor&). - Remove redundant
inspectorCommonStylesortextButtonStylesimports from Light DOM views (installComponentRootStyles()already provides them). For other shared stylesheets, wrap inline as<style>@scope to (devtools-widget > *) { ${styles} }</style>. - Beware that the
(devtools-widget > *)lower boundary stops cascading into declarative<devtools-widget>children (${widget(...)}), but does not stop at imperatively attachedchildWidget.show(container)legacy children.
- Render Templates Syntax & Code Movement:
- Surround the expressions containing lit template literals with `//
clang-format off and // clang-format on` to prevent clang-format from
corrupting template indentation.
- Minimize Code Movement: Avoid moving existing code to a different location in the file. Put the function signature around the existing code to minimize the diff.
- The Gerrit Code Review UI cannot identify moved blocks of unchanged code.
- If blocks of code need to be reordered, create a "prefactoring" change that first extracts the code that needs to be reordered into a named helper functions and pause the migration, waiting user confirmation.
- Composing Child
UI.Widgets & Pre-Existing Instances:
- Prefer
${widget(ChildWidgetClass, {params})}Over<devtools-widget>:
Prefer ${widget(ChildWidgetClass, {params})} directly as a child
expression instead of <devtools-widget ${widget(ChildWidgetClass, {params})}></devtools-widget>.
Only use an explicit <devtools-widget> tag when you need to set other
HTML attributes/classes, apply additional directives (such as widgetRef
or ref), or provide child nodes.
- Strongly Prefer Two-Argument
widget(ChildWidgetClass, {params}):
When instantiating child widgets in a Lit template, strongly prefer the
two-argument form widget(ChildWidgetClass, {propA: input.a, propB: input.b})
over the single-argument factory widget(element => new ChildWidgetClass(element)).
The two-argument form automatically propagates updated parameters and
schedules requestUpdate() on re-renders, whereas a factory callback only
runs once on initial creation. If the child widget currently uses
setFoo() methods instead of setters, convert them into set foo()
setters on the child widget so you can use the two-argument widget()
directive.
- No Widget References on
ViewOutput: Do not store child widget
references on ViewOutput (e.g., output.childWidget = w) as a final
result (only acceptable temporarily in intermediate CLs). Supply all
configuration through setters on the child widget, or if imperative
actions are strictly required, expose individual functions on ViewOutput
(e.g., output.doLayout = () => w.doLayout()).
- Avoid
UI.Widget.WrapperWidget: Do NOT instantiate child widgets
or layout containers (new ChildWidget(), UI.TabbedPane.TabbedPane /
tabbedLocation.tabbedPane(), StackLocation.widget(),
UI.ListWidget.ListWidget, UI.SplitWidget.SplitWidget) in the
constructor/presenter and pass them via ViewInput to
UI.Widget.WrapperWidget.
- Child widgets: Refactor the child widget to accept
element?: HTMLElement in its constructor and setters for its state,
and instantiate it declaratively 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> instead of wrapping a TabbedPane or
StackLocation.widget() in WrapperWidget.
- Migrating
UI.ListWidget.ListWidget+UI.ListWidget.Delegate: Do
NOT keep this.list = new UI.ListWidget.ListWidget(this) and `implements
UI.ListWidget.Delegate on the presenter, convert renderItem` /
beginEdit to render into a DocumentFragment, and pass list via
ViewInput to WrapperWidget. Instead:
1. Recommended: Replace ListWidget + ListWidget.Delegate with
<devtools-list> (ui/components/lists/lists.js), passing pure data
(items, editingIndex, validationError) and callbacks in
ViewInput, and handling editing via <devtools-prompt>, an inline
editor row, or UI.Dialog.Dialog.
2. **Incremental fallback (if preserving ListWidget.Editor screenshot
goldens temporarily)**: Move ListWidget + ListWidget.Delegate
ownership out of the presenter into a view-layer child class
extending UI.ListWidget.ListWidget directly and instantiated via
${widget(...)} in DEFAULT_VIEW (with an imperative trigger on
ViewOutput if needed, and without WrapperWidget), keeping
ViewInput pure data and callbacks.
WrapperWidgetis only justified when reparenting a shared stateful
singleton across multiple containers (such as ConsoleView.instance()
or SourcesView) or bridging an opaque UI.Widget returned by an
external factory. Note that WrapperWidget sets display: contents on
its <devtools-widget> host, so never put sizing, border, or background
classes on the <devtools-widget> hosting WrapperWidget (wrap it in a
<div> instead).
- Declarative
<devtools-split-view>Guidelines:
- CSS Sizing: Ensure
<devtools-split-view>hasflex: auto; height: 100%;
in CSS so it fills available container space and doesn't collapse to 0x0.
- Reuse Existing Settings for
showMode: When bindingshow=${...}
declaratively on <devtools-split-view name="...">, reuse the existing
SplitWidget setting ({vertical?: {size, showMode}, horizontal?: {size, showMode}})
for showMode rather than creating new boolean settings (which loses user
preferences and requires KnownContextValues.ts updates).
- Keep Environment Overrides in Templates: Keep environment overrides
(like !input.isTraceApp) in the DEFAULT_VIEW template (e.g.,
show=${!input.isTraceApp && input.isSidebarOpen ? 'both' : 'main'})
rather than baking them into the presenter's setting state.
- Guard
@changeAgainst Bubbling NativechangeEvents: Always guard
<devtools-split-view> @change listeners with
if (e.target === e.currentTarget && e instanceof CustomEvent) before
reading e.detail. SplitWidgetElement dispatches a non-bubbling
CustomEvent('change', {detail: showMode}) on itself, whereas native
<input> and <select> controls inside light-DOM child slots dispatch
bubbling Event('change') events with e.detail === undefined.
- Clean Up Resizers: Do not leave unused
resizer-widgetclasses in
templates; <devtools-split-view> manages its own built-in splitter
unless custom elements are explicitly registered with installResizer.
- Declarative Long-Press Action Buttons (
bindToAction):
- Legacy
UI.Toolbar.Toolbar.createLongPressActionButton(action, [subButtons])
maps declaratively to nesting option <devtools-button> elements directly
inside <devtools-button ${bindToAction('action-id')}>...</devtools-button>.
- Audit Removed
UIStrings:
- If a
UIStringsentry becomes unused during template migration, verify
that a conditional UI branch (such as a dynamically shown checkbox, button,
or tooltip) wasn't accidentally dropped before deleting the string.
- Micro-Commit Strategy:
- Do not attempt to convert every helper method and UI component in a single monolithic commit. Break the template extraction into small, self-contained micro-commits (e.g., migrating one helper method, toolbar button, or list item render at a time).
- Verify with build and run tests after each micro-commit to guarantee zero regressions and 100% visual parity before moving to the next compartment.
- Use
--no-fixWhen Linting Partially Migrated Classes:./dt lintrunseslint --fix. While imperativethis.element/this.contentElementmutations still remain in a partially migrated class, pass--no-fixso@devtools/no-imperative-dom-api's autofixer does not insert duplicateexport const DEFAULT_VIEWstubs or rewritedocument.createElementinto invalidTemplateResultcode. - Provide the exact list of files and commit message when presenting progress so the change history remains atomic and easy to review.
- Wait for confirmation:
- Wait for an explicit confirmation from the user (or Parent Orchestrator Agent) before proceeding to the next step.
🔍 Mental Audit (Internal Self-Correction)
Before reporting back or committing, re-read the instructions and verify:
- ❓ Named Imports: Did I use named imports
{html, nothing, render}fromui/lit/lit.js(and noimport * as Lit)? - ❓ Tag Parity: Did I accidentally change any
spantodiv(or vice versa)? - ❓ Attribute Drop: Did I drop any
aria-*,role, or custom data attributes? - ❓ Clang-Off Boundary: Is the template wrapped in
// clang-format off? - ❓ Split Views: Does
<devtools-split-view>haveflex: auto; height: 100%;CSS and reuse existing split settings? - ❓ String Audit: Did I verify that any removed
UIStringsweren't from accidentally dropped UI branches? - ❓ Build: Does the code compile and do visual tests pass with 0% diff?
- ❓ CSS @scope Encapsulation: Are Light DOM styles wrapped in
@scope to (devtools-widget > *)with:scopeinstead of:host, theme-aware--sys-color-*tokens instead of theme classes, redundant common styles removed, and no entries added to the ESLint burndown list?