MCPcopy Create free account
hub / github.com/TanStack/devtools / createHeadChanges

Function createHeadChanges

packages/devtools/src/hooks/use-head-changes.ts:37–110  ·  view source on GitHub ↗
(
  onChange: (change: HeadChange, raw?: MutationRecord) => void,
  opts: UseHeadChangesOptions = {},
)

Source from the content-addressed store, hash-verified

35}
36
37/**
38 * A `<style>` tag in `<head>` never carries SEO metadata, and CSS-in-JS
39 * libraries write into one constantly — goober alone re-stamps its `nonce`
40 * attribute and rewrites its text on every `css()` call. Reporting those as head
41 * changes feeds a loop: the consumer re-renders, the re-render emits CSS, the
42 * CSS mutates `<head>`, and the observer fires again. Stylesheets are filtered
43 * out so only real metadata reaches the consumer.
44 */
45const isStyleNode = (node: Node): boolean => {
46 const element =
47 node.nodeType === 3 /* Node.TEXT_NODE */ ? node.parentNode : node
48 return (element as Element | null)?.nodeName === 'STYLE'
49}
50
51export function createHeadChanges(
52 onChange: (change: HeadChange, raw?: MutationRecord) => void,
53 opts: UseHeadChangesOptions = {},
54) {
55 const {
56 attributes = true,
57 childList = true,
58 subtree = true,
59 observeTitle = true,
60 } = opts
61
62 onSettled(() => {
63 const headObserver = new MutationObserver((mutations) => {
64 for (const m of mutations) {
65 if (m.type === 'childList') {
66 m.addedNodes.forEach((node) => {
67 if (!isStyleNode(node)) onChange({ kind: 'added', node }, m)
68 })
69 m.removedNodes.forEach((node) => {
70 if (!isStyleNode(node)) onChange({ kind: 'removed', node }, m)
71 })
72 } else if (m.type === 'attributes') {
73 if (isStyleNode(m.target)) continue
74 const el = m.target as Element
75 onChange(
76 {
77 kind: 'attr',
78 target: el,
79 name: m.attributeName,
80 oldValue: m.oldValue ?? null,
81 },
82 m,
83 )
84 } else {
85 // If someone mutates a Text node inside <title>, surface it as a title change.
86 const isInTitle =
87 m.target.parentNode &&
88 (m.target.parentNode as Element).tagName.toLowerCase() === 'title'
89 if (isInTitle) onChange({ kind: 'title', title: document.title }, m)
90 }
91 }
92 })
93
94 headObserver.observe(document.head, {

Callers 2

SerpPreviewSectionFunction · 0.90
SocialPreviewsSectionFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected