Skip to content
Draft
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
8 changes: 8 additions & 0 deletions .changeset/perf-avatarstack-has-selector.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@primer/react': patch
---

perf(AvatarStack): Optimize CSS :has() selector and throttle MutationObserver

- Scope `:has([data-square])` to direct child with `>` combinator for O(1) lookup
- Throttle MutationObserver callback using requestAnimationFrame to batch DOM reads
3 changes: 2 additions & 1 deletion packages/react/src/AvatarStack/AvatarStack.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@
box-shadow: 0 0 0 var(--avatar-border-width) transparent;
}

&:not([data-component='Avatar']):not(:has([data-square])) {
/* PERFORMANCE: Avatar with data-square is direct child, scope with > for O(1) lookup */
&:not([data-component='Avatar']):not(:has(> [data-square])) {
border-radius: 50%;
}

Expand Down
17 changes: 16 additions & 1 deletion packages/react/src/AvatarStack/AvatarStack.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,19 @@ const AvatarStack = ({
setHasInteractiveChildren(hasInteractiveNodes(stackContainer.current))
}

const observer = new MutationObserver(interactiveChildren)
// Track pending frame to throttle MutationObserver callbacks
let pendingFrame: number | null = null
const throttledInteractiveChildren = () => {
if (pendingFrame !== null) {
cancelAnimationFrame(pendingFrame)
}
pendingFrame = requestAnimationFrame(() => {
pendingFrame = null
interactiveChildren()
})
}

const observer = new MutationObserver(throttledInteractiveChildren)

observer.observe(stackContainer.current, {childList: true})

Expand All @@ -129,6 +141,9 @@ const AvatarStack = ({

return () => {
observer.disconnect()
if (pendingFrame !== null) {
cancelAnimationFrame(pendingFrame)
}
}
}
}, [])
Expand Down
Loading