Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/devtools-overlay-perf.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"js.foresight-devtools": patch
---

Faster devtools with many elements: the elements tab only renders visible rows (10,000 elements went from over a million DOM nodes to under 50,000), page overlays no longer write to the DOM while scrolling or force a layout per element, animations are compositor-only, and hidden overlays no longer process updates
33 changes: 33 additions & 0 deletions packages/devpage-framework/src/vue/views/mass/ButtonGrid.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<script setup lang="ts">
import { Foresight } from "@foresightjs/vue"

defineProps<{ buttonCount: number }>()
const emit = defineEmits<{ hit: [] }>()

Check failure on line 5 in packages/devpage-framework/src/vue/views/mass/ButtonGrid.vue

View workflow job for this annotation

GitHub Actions / lint

defineEmits should be placed at the top of `<script setup>` (after any potential import statements or type definitions)
Comment on lines +4 to +5

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

vue/define-macros-order is configured with ["defineModel", "defineEmits", "defineSlots"], so defineEmits has to precede defineProps. As written pnpm lint fails here, and that is one of the two errors keeping the lint check red on this PR — swapping the two lines (or running eslint --fix) clears it.


const onHit = () => emit("hit")
</script>

<template>
<div class="flex flex-wrap gap-1">
<Foresight
v-for="i in buttonCount"
:key="i"
:hit-slop="0"
:callback="onHit"
#default="{ elementRef, isPredicted }"
>
<button
type="button"
:ref="elementRef"
:class="[
'flex justify-center items-center size-10 text-xs font-medium border',
isPredicted
? 'bg-emerald-500 text-white border-emerald-600'
: 'bg-white text-gray-700 border-gray-300',
]"
>
{{ i - 1 }}
</button>
</Foresight>
</div>
</template>
27 changes: 3 additions & 24 deletions packages/devpage-framework/src/vue/views/mass/index.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { ref } from "vue"
import { Foresight } from "@foresightjs/vue"
import ButtonGrid from "./ButtonGrid.vue"

const resetKey = ref(0)
const hitCount = ref(0)
Expand Down Expand Up @@ -52,28 +52,7 @@
</div>
</div>

<!-- Re-keying the container on reset re-mounts every button, clearing state. -->
<div :key="resetKey" class="flex flex-wrap gap-1">
<Foresight
v-for="i in buttonCount"
:key="i"
:hit-slop="0"
:callback="onHit"
#default="{ elementRef, isPredicted }"
>
<button
type="button"
:ref="elementRef"
:class="[
'flex justify-center items-center size-10 text-xs font-medium border',
isPredicted
? 'bg-emerald-500 text-white border-emerald-600'
: 'bg-white text-gray-700 border-gray-300',
]"
>
{{ i - 1 }}
</button>
</Foresight>
</div>
<!-- Re-keying the grid on reset re-mounts every button, clearing state. -->
<ButtonGrid :key="resetKey" :button-count="buttonCount" @hit="onHit" />

Check failure on line 56 in packages/devpage-framework/src/vue/views/mass/index.vue

View workflow job for this annotation

GitHub Actions / lint

Expected same-name shorthand

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

vue/v-bind-style with sameNameShorthand: "always" wants the shorthand form here, and this is the second error in the red lint job. eslint --fix rewrites the line to :button-count (the compiler camelizes the name to form the expression).

</main>
</template>
3 changes: 2 additions & 1 deletion packages/js.foresight-devtools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,13 @@
"devDependencies": {
"@types/node": "^26.6.5",
"js.foresight": "workspace:*",
"tslib": "^2.8.1",
"tsdown": "^0.23.1",
"tslib": "^2.8.1",
"typescript": "^6.0.3",
"vitest": "^5.0.5"
},
"dependencies": {
"@lit-labs/virtualizer": "^2.1.1",
"lit": "^3.3.3"
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { css, html, LitElement } from "lit"
import { customElement, state } from "lit/decorators.js"
import { repeat } from "lit/directives/repeat.js"
import { virtualize } from "@lit-labs/virtualizer/virtualize.js"

import type {
CallbackInvokedEvent,
Expand All @@ -9,7 +9,10 @@ import type {
} from "js.foresight"
import { ForesightManager, type ForesightElement, type ForesightElementState } from "js.foresight"

type ElementListEntry = { element: ForesightElement; state: ForesightElementState }
type Section = "active" | "inactive"
type ListRow =
| { kind: "header"; section: Section; count: number }
| { kind: "element"; element: ForesightElement; state: ForesightElementState }
import { CHEVRON_SVG } from "../../../svg/svg-icons"
import type { SortElementList } from "../../../types/types"
import type { CallbackHits } from "../../../helpers/callbackHits"
Expand All @@ -33,7 +36,20 @@ export class ElementTab extends LitElement {
height: 100%;
}

.section + .section {
/* The list scrolls itself: the virtualizer looks up its scroll container
on connect, before tab-content has rendered the slot it sits in. */
.list {
height: 100%;
scrollbar-width: thin;
scrollbar-color: var(--fs-line) transparent;
}

/* The virtualizer positions rows absolutely, so they need an explicit width. */
single-element {
width: 100%;
}

.section-header.inactive-header {
margin-top: 8px;
}

Expand Down Expand Up @@ -95,6 +111,7 @@ export class ElementTab extends LitElement {
private _cachedActiveElements: ForesightElement[] = []
private _cachedInactiveElements: ForesightElement[] = []
private _elementsCacheDirty = true
private _documentOrder: ForesightElement[] | null = null

constructor() {
super()
Expand Down Expand Up @@ -234,6 +251,7 @@ export class ElementTab extends LitElement {
this.elementListItems.set(e.element, e.state)
this._subscribeToElement(e.element)
this._elementsCacheDirty = true
this._documentOrder = null
this.requestUpdate()
},
{ signal }
Expand All @@ -247,6 +265,7 @@ export class ElementTab extends LitElement {
// Drop any queued update so a later debounce flush can't re-add it.
this._pendingElementUpdates.delete(e.element)
this._elementsCacheDirty = true
this._documentOrder = null
this.requestUpdate()
},
{ signal }
Expand Down Expand Up @@ -310,6 +329,10 @@ export class ElementTab extends LitElement {
// membership, isActive and isIntersectingWithViewport.
for (const [element, state] of this._pendingElementUpdates) {
const previous = this.elementListItems.get(element)
if (previous?.isParked !== state.isParked) {
this._documentOrder = null
}

if (
!previous ||
previous.isActive !== state.isActive ||
Expand All @@ -327,31 +350,46 @@ export class ElementTab extends LitElement {
private updateElementListFromManager() {
this.elementListItems = new Map(ForesightManager.instance.registeredElements)
this._elementsCacheDirty = true
this._documentOrder = null
}

private getSortedElements(): ElementListEntry[] {
const entries: ElementListEntry[] = Array.from(this.elementListItems, ([element, state]) => ({
element,
state,
}))
private get documentOrder(): ForesightElement[] {
if (this._documentOrder) {
return this._documentOrder
}

const unplaced = new Set(this.elementListItems.keys())
const ordered: ForesightElement[] = []
for (const node of document.querySelectorAll("*")) {
if (unplaced.delete(node)) {
ordered.push(node)
}
}
ordered.push(...unplaced)
this._documentOrder = ordered

return ordered
}
Comment on lines +356 to +372

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cache is invalidated on register/unregister and on park transitions, but not when an already-registered element moves in the DOM: a framework reordering keyed children leaves the node connected, so it is never parked and the cached order keeps its old position. by document / by visibility then show a stale order until the next register or unregister — low stakes for a debug view, but staler than main, which re-sorted on every dirty recompute.

Technical details
# Stale document order after DOM moves

## Affected sites
- `packages/js.foresight-devtools/src/lit-entry/control-panel/element-tab/element-tab.ts:356-372` — `documentOrder` caches one DOM walk; only registration and `isParked` flips null it.

## Required outcome
- The cached order must not outlive a move/reorder of elements that are already registered and connected.

## Suggested approach (optional)
- Null `_documentOrder` when the manager's document `MutationObserver` reports a childList change (that is the same signal it uses to park/reconnect), or rebuild the order inside `_recomputeElementsCache` if the walk is cheap enough for the target DOM sizes.


private getSortedElements(): ForesightElement[] {
switch (this.sortOrder) {
case "insertionOrder":
return entries
return [...this.elementListItems.keys()]
case "documentOrder":
return entries.sort(this.sortByDocumentPosition)
case "visibility":
return entries.sort((a, b) => {
if (a.state.isIntersectingWithViewport !== b.state.isIntersectingWithViewport) {
return a.state.isIntersectingWithViewport ? -1 : 1
}

return this.sortByDocumentPosition(a, b)
})
return this.documentOrder
case "visibility": {
const isVisible = (element: ForesightElement) =>
this.elementListItems.get(element)?.isIntersectingWithViewport === true

return [
...this.documentOrder.filter(isVisible),
...this.documentOrder.filter(element => !isVisible(element)),
]
}
default:
this.sortOrder satisfies never

return entries
return []
}
}

Expand All @@ -362,13 +400,13 @@ export class ElementTab extends LitElement {

const active: ForesightElement[] = []
const inactive: ForesightElement[] = []
for (const entry of this.getSortedElements()) {
for (const element of this.getSortedElements()) {
// Disabled elements are inactive too; their reason is shown as a badge on the
// row rather than a separate section.
if (entry.state.isActive) {
active.push(entry.element)
if (this.elementListItems.get(element)?.isActive) {
active.push(element)
} else {
inactive.push(entry.element)
inactive.push(element)
}
}
this._cachedActiveElements = active
Expand All @@ -388,59 +426,58 @@ export class ElementTab extends LitElement {
return this._cachedInactiveElements
}

private sortByDocumentPosition = (a: ElementListEntry, b: ElementListEntry) => {
const position = a.element.compareDocumentPosition(b.element)
if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
return -1
private toggleSection(section: Section): void {
if (section === "active") {
this.activeSectionCollapsed = !this.activeSectionCollapsed
} else {
this.inactiveSectionCollapsed = !this.inactiveSectionCollapsed
}
}

private sectionRows(section: Section, elements: ForesightElement[]): ListRow[] {
if (elements.length === 0) {
return []
}

if (position & Node.DOCUMENT_POSITION_PRECEDING) {
return 1
const collapsed =
section === "active" ? this.activeSectionCollapsed : this.inactiveSectionCollapsed
const rows: ListRow[] = [{ kind: "header", section, count: elements.length }]
if (collapsed) {
return rows
}

return 0
for (const element of elements) {
const state = this.elementListItems.get(element)
if (state) {
rows.push({ kind: "element", element, state })
}
}

return rows
}

private renderElementSection(
label: string,
elements: ForesightElement[],
collapsed: boolean,
toggleCollapsed: () => void
) {
if (elements.length === 0) {
return ""
private renderRow = (row: ListRow) => {
if (row.kind === "element") {
return html`
<single-element
.element=${row.element}
.state=${row.state}
.isExpanded=${this.expandedElementIds.has(row.state.id)}
.onToggle=${this.handleElementToggle}
></single-element>
`
}

const collapsed =
row.section === "active" ? this.activeSectionCollapsed : this.inactiveSectionCollapsed

return html`
<div class="section">
<button class="section-header ${collapsed ? "collapsed" : ""}" @click=${toggleCollapsed}>
${CHEVRON_SVG} ${label}<span class="rule"></span>${elements.length}
</button>
${
!collapsed
? repeat(
elements,
element => this.elementListItems.get(element)?.id ?? "",
element => {
const state = this.elementListItems.get(element)
if (!state) {
return ""
}

return html`
<single-element
.element=${element}
.state=${state}
.isExpanded=${this.expandedElementIds.has(state.id)}
.onToggle=${this.handleElementToggle}
>
</single-element>
`
}
)
: ""
}
</div>
<button
class="section-header ${row.section}-header ${collapsed ? "collapsed" : ""}"
@click=${() => this.toggleSection(row.section)}
>
${CHEVRON_SVG} ${row.section}<span class="rule"></span>${row.count}
</button>
`
}

Expand All @@ -461,22 +498,17 @@ export class ElementTab extends LitElement {
</div>
</tab-header>
<tab-content .noContentMessage=${EMPTY_MESSAGE} .hasContent=${!!this.elementListItems.size}>
${this.renderElementSection(
"active",
this.activeElements,
this.activeSectionCollapsed,
() => {
this.activeSectionCollapsed = !this.activeSectionCollapsed
}
)}
${this.renderElementSection(
"inactive",
this.inactiveElements,
this.inactiveSectionCollapsed,
() => {
this.inactiveSectionCollapsed = !this.inactiveSectionCollapsed
}
)}
<div class="list">
${virtualize({
scroller: true,
items: [
...this.sectionRows("active", this.activeElements),
...this.sectionRows("inactive", this.inactiveElements),
],
keyFunction: row => (row.kind === "header" ? row.section : row.state.id),
renderItem: this.renderRow,
})}
</div>
</tab-content>
`
}
Expand Down
Loading
Loading