@buoy-gg/highlight-updates 7.0.41 → 7.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +11 -71
  2. package/lib/commonjs/highlight-updates/HighlightUpdatesOverlay.js +1 -281
  3. package/lib/commonjs/highlight-updates/components/HighlightFilterView.js +1 -1474
  4. package/lib/commonjs/highlight-updates/components/HighlightUpdatesModal.js +1 -641
  5. package/lib/commonjs/highlight-updates/components/IdentifierBadge.js +1 -273
  6. package/lib/commonjs/highlight-updates/components/IsolatedRenderList.js +1 -188
  7. package/lib/commonjs/highlight-updates/components/ModalHeaderContent.js +1 -293
  8. package/lib/commonjs/highlight-updates/components/RenderCauseBadge.js +1 -508
  9. package/lib/commonjs/highlight-updates/components/RenderDetailView.js +1 -846
  10. package/lib/commonjs/highlight-updates/components/RenderHistoryViewer.js +1 -915
  11. package/lib/commonjs/highlight-updates/components/RenderListItem.js +1 -235
  12. package/lib/commonjs/highlight-updates/components/RendersCopySettingsView.js +1 -469
  13. package/lib/commonjs/highlight-updates/components/StatsDisplay.js +1 -73
  14. package/lib/commonjs/highlight-updates/types/copySettings.js +1 -107
  15. package/lib/commonjs/highlight-updates/utils/CommitProfiler.js +1 -455
  16. package/lib/commonjs/highlight-updates/utils/HighlightUpdatesController.js +1 -1929
  17. package/lib/commonjs/highlight-updates/utils/PerformanceLogger.js +26 -359
  18. package/lib/commonjs/highlight-updates/utils/ProfilerInterceptor.js +1 -371
  19. package/lib/commonjs/highlight-updates/utils/RenderCauseDetector.js +5 -1840
  20. package/lib/commonjs/highlight-updates/utils/RenderTracker.js +1 -952
  21. package/lib/commonjs/highlight-updates/utils/ViewTypeMapper.js +1 -264
  22. package/lib/commonjs/highlight-updates/utils/copySettingsStorage.js +1 -32
  23. package/lib/commonjs/highlight-updates/utils/devtoolsComponentNames.js +1 -188
  24. package/lib/commonjs/highlight-updates/utils/namedComposite.js +1 -41
  25. package/lib/commonjs/highlight-updates/utils/ownStateChanged.js +1 -103
  26. package/lib/commonjs/highlight-updates/utils/rawEventEmitter.js +1 -50
  27. package/lib/commonjs/highlight-updates/utils/rawEventEmitter.web.js +1 -12
  28. package/lib/commonjs/highlight-updates/utils/renderExportFormatter.js +1 -58
  29. package/lib/commonjs/highlight-updates/utils/rendersExportFormatter.js +1 -485
  30. package/lib/commonjs/highlight-updates/utils/screenElements.js +1 -1269
  31. package/lib/commonjs/highlight-updates/utils/tapMatch.js +1 -83
  32. package/lib/commonjs/highlight-updates/utils/testIDs.js +1 -68
  33. package/lib/commonjs/highlight-updates/utils/touchCapture.js +1 -277
  34. package/lib/commonjs/index.js +1 -429
  35. package/lib/commonjs/preset.js +1 -278
  36. package/lib/commonjs/sync/highlightUpdatesSyncAdapter.js +1 -235
  37. package/lib/module/highlight-updates/HighlightUpdatesOverlay.js +1 -274
  38. package/lib/module/highlight-updates/components/HighlightFilterView.js +1 -1468
  39. package/lib/module/highlight-updates/components/HighlightUpdatesModal.js +1 -634
  40. package/lib/module/highlight-updates/components/IdentifierBadge.js +1 -265
  41. package/lib/module/highlight-updates/components/IsolatedRenderList.js +1 -183
  42. package/lib/module/highlight-updates/components/ModalHeaderContent.js +1 -288
  43. package/lib/module/highlight-updates/components/RenderCauseBadge.js +1 -499
  44. package/lib/module/highlight-updates/components/RenderDetailView.js +1 -840
  45. package/lib/module/highlight-updates/components/RenderHistoryViewer.js +1 -908
  46. package/lib/module/highlight-updates/components/RenderListItem.js +1 -230
  47. package/lib/module/highlight-updates/components/RendersCopySettingsView.js +1 -465
  48. package/lib/module/highlight-updates/components/StatsDisplay.js +1 -70
  49. package/lib/module/highlight-updates/types/copySettings.js +1 -102
  50. package/lib/module/highlight-updates/utils/CommitProfiler.js +1 -451
  51. package/lib/module/highlight-updates/utils/HighlightUpdatesController.js +1 -1925
  52. package/lib/module/highlight-updates/utils/PerformanceLogger.js +26 -353
  53. package/lib/module/highlight-updates/utils/ProfilerInterceptor.js +1 -358
  54. package/lib/module/highlight-updates/utils/RenderCauseDetector.js +5 -1830
  55. package/lib/module/highlight-updates/utils/RenderTracker.js +1 -949
  56. package/lib/module/highlight-updates/utils/ViewTypeMapper.js +1 -255
  57. package/lib/module/highlight-updates/utils/copySettingsStorage.js +1 -26
  58. package/lib/module/highlight-updates/utils/devtoolsComponentNames.js +1 -178
  59. package/lib/module/highlight-updates/utils/namedComposite.js +1 -36
  60. package/lib/module/highlight-updates/utils/ownStateChanged.js +1 -98
  61. package/lib/module/highlight-updates/utils/rawEventEmitter.js +1 -46
  62. package/lib/module/highlight-updates/utils/rawEventEmitter.web.js +1 -3
  63. package/lib/module/highlight-updates/utils/renderExportFormatter.js +1 -54
  64. package/lib/module/highlight-updates/utils/rendersExportFormatter.js +1 -478
  65. package/lib/module/highlight-updates/utils/screenElements.js +1 -1263
  66. package/lib/module/highlight-updates/utils/tapMatch.js +1 -76
  67. package/lib/module/highlight-updates/utils/testIDs.js +1 -60
  68. package/lib/module/highlight-updates/utils/touchCapture.js +1 -270
  69. package/lib/module/index.js +1 -130
  70. package/lib/module/preset.js +1 -272
  71. package/lib/module/sync/highlightUpdatesSyncAdapter.js +1 -230
  72. package/lib/web/index.mjs +28 -29
  73. package/package.json +7 -7
  74. package/lib/typescript/highlight-updates/HighlightUpdatesOverlay.d.ts.map +0 -1
  75. package/lib/typescript/highlight-updates/components/HighlightFilterView.d.ts.map +0 -1
  76. package/lib/typescript/highlight-updates/components/HighlightUpdatesModal.d.ts.map +0 -1
  77. package/lib/typescript/highlight-updates/components/IdentifierBadge.d.ts.map +0 -1
  78. package/lib/typescript/highlight-updates/components/IsolatedRenderList.d.ts.map +0 -1
  79. package/lib/typescript/highlight-updates/components/ModalHeaderContent.d.ts.map +0 -1
  80. package/lib/typescript/highlight-updates/components/RenderCauseBadge.d.ts.map +0 -1
  81. package/lib/typescript/highlight-updates/components/RenderDetailView.d.ts.map +0 -1
  82. package/lib/typescript/highlight-updates/components/RenderHistoryViewer.d.ts.map +0 -1
  83. package/lib/typescript/highlight-updates/components/RenderListItem.d.ts.map +0 -1
  84. package/lib/typescript/highlight-updates/components/RendersCopySettingsView.d.ts.map +0 -1
  85. package/lib/typescript/highlight-updates/components/StatsDisplay.d.ts.map +0 -1
  86. package/lib/typescript/highlight-updates/types/copySettings.d.ts.map +0 -1
  87. package/lib/typescript/highlight-updates/utils/CommitProfiler.d.ts.map +0 -1
  88. package/lib/typescript/highlight-updates/utils/HighlightUpdatesController.d.ts.map +0 -1
  89. package/lib/typescript/highlight-updates/utils/PerformanceLogger.d.ts.map +0 -1
  90. package/lib/typescript/highlight-updates/utils/ProfilerInterceptor.d.ts.map +0 -1
  91. package/lib/typescript/highlight-updates/utils/RenderCauseDetector.d.ts.map +0 -1
  92. package/lib/typescript/highlight-updates/utils/RenderTracker.d.ts.map +0 -1
  93. package/lib/typescript/highlight-updates/utils/ViewTypeMapper.d.ts.map +0 -1
  94. package/lib/typescript/highlight-updates/utils/copySettingsStorage.d.ts.map +0 -1
  95. package/lib/typescript/highlight-updates/utils/devtoolsComponentNames.d.ts.map +0 -1
  96. package/lib/typescript/highlight-updates/utils/namedComposite.d.ts.map +0 -1
  97. package/lib/typescript/highlight-updates/utils/ownStateChanged.d.ts.map +0 -1
  98. package/lib/typescript/highlight-updates/utils/rawEventEmitter.d.ts.map +0 -1
  99. package/lib/typescript/highlight-updates/utils/rawEventEmitter.web.d.ts.map +0 -1
  100. package/lib/typescript/highlight-updates/utils/renderExportFormatter.d.ts.map +0 -1
  101. package/lib/typescript/highlight-updates/utils/rendersExportFormatter.d.ts.map +0 -1
  102. package/lib/typescript/highlight-updates/utils/screenElements.d.ts.map +0 -1
  103. package/lib/typescript/highlight-updates/utils/tapMatch.d.ts.map +0 -1
  104. package/lib/typescript/highlight-updates/utils/testIDs.d.ts.map +0 -1
  105. package/lib/typescript/highlight-updates/utils/touchCapture.d.ts.map +0 -1
  106. package/lib/typescript/index.d.ts.map +0 -1
  107. package/lib/typescript/preset.d.ts.map +0 -1
  108. package/lib/typescript/sync/highlightUpdatesSyncAdapter.d.ts.map +0 -1
@@ -1,1925 +1 @@
1
- "use strict";
2
-
3
- import { getDOMFiber, getDOMNodeHandle, getDOMPublicInstance, isDOMElement } from "@buoy-gg/shared-ui/utils";
4
- /**
5
- * Highlight Updates Controller
6
- *
7
- * Standalone implementation that replicates React DevTools' "Highlight updates
8
- * when components render" feature WITHOUT requiring DevTools to be connected.
9
- *
10
- * Architecture:
11
- * This controller directly enables the DevTools backend's traceUpdates feature
12
- * by calling setTraceUpdatesEnabled(true) on each renderer interface. This is
13
- * the same function that DevTools' frontend calls when you check the
14
- * "Highlight updates when components render" checkbox.
15
- *
16
- * Key insight: The rendererInterfaces are available on the global hook even
17
- * without DevTools frontend connected. We just need to enable tracing directly.
18
- *
19
- * Flow:
20
- * 1. User enables highlights via toggle()
21
- * 2. We call rendererInterface.setTraceUpdatesEnabled(true) on all renderers
22
- * 3. DevTools backend now tracks renders and emits 'traceUpdates' events
23
- * 4. We subscribe to 'traceUpdates' via hook.sub()
24
- * 5. When components re-render, we receive the Set of host stateNodes
25
- * 6. We measure each node and render colored border highlights
26
- *
27
- * This gives us 100% accuracy with DevTools behavior because we're using the
28
- * exact same detection code - we're just enabling it programmatically.
29
- */
30
-
31
- "use strict";
32
- import { installProfilerInterceptor, uninstallProfilerInterceptor, setComparisonCallback } from "./ProfilerInterceptor";
33
- import { findNodeHandle, UIManager, Dimensions, PixelRatio } from "react-native";
34
- import { RenderTracker } from "./RenderTracker";
35
- import { describeScreen } from "./screenElements";
36
- import { scoreTapMatch } from "./tapMatch";
37
- import { PerformanceLogger, markEventReceived } from "./PerformanceLogger";
38
- import { detectRenderCause, clearRenderCauseState } from "./RenderCauseDetector";
39
- import { notifySubscriberCountChange } from "@buoy-gg/shared-ui";
40
- import { HIGHLIGHT_OVERLAY_COMPONENTS, HIGHLIGHT_OVERLAY_PREFIXES, OTHER_DEV_TOOLS_COMPONENTS, OTHER_DEV_TOOLS_EXACT, OTHER_DEV_TOOLS_PREFIXES, isCapturingBuoyToolRenders, isPerfMonitorComponentName } from "./devtoolsComponentNames";
41
- // State
42
- let globalEnabled = false; // User-controlled toggle for visual highlights
43
- // When true, tracking + measurement + storage all run as normal, but the
44
- // visual highlight boxes are NOT drawn. Lets the desktop "screenshot this
45
- // component" flow get the render history + measurements with no on-device
46
- // overlay. Independent of globalEnabled; reset whenever the visual tool is
47
- // enabled (the Renders tab always wants its boxes).
48
- let highlightsSuppressed = false;
49
- let backgroundTrackingEnabled = false; // Auto-enabled when event callbacks exist (Events tool)
50
- let initialized = false;
51
- let hook = null;
52
- let highlightCallback = null;
53
- let badgePressCallback = null;
54
- let traceUpdatesUnsubscribe = null;
55
- let isProcessing = false;
56
-
57
- // Freeze frame state
58
- let isFrozen = false;
59
- const freezeListeners = new Set();
60
- const stateListeners = new Set();
61
-
62
- // Track render counts per node (for color assignment like DevTools)
63
- // Map from nativeTag to render count - nativeTag is stable across re-renders
64
- const nodeRenderCounts = new Map();
65
-
66
- // Color palette for highlights (same as DevTools)
67
- // From: react-devtools-core/dist/backend.js line 6361
68
- const COLORS = ["#37afa9", "#63b19e", "#80b393", "#97b488", "#abb67d", "#beb771", "#cfb965", "#dfba57", "#efbb49", "#febc38"];
69
-
70
- // Set to true for verbose debugging of our implementation
71
- // Disabled for now to focus on profiler logs only
72
- const DEBUG = false;
73
- function debugLog(message, data) {
74
- if (!DEBUG) return;
75
- if (data !== undefined) {
76
- console.log(`[HighlightUpdates] ${message}`, data);
77
- } else {
78
- console.log(`[HighlightUpdates] ${message}`);
79
- }
80
- }
81
-
82
- /**
83
- * Get the public instance from a stateNode (the node passed in traceUpdates)
84
- */
85
- function getPublicInstance(stateNode) {
86
- const dom = getDOMPublicInstance(stateNode);
87
- if (dom) return dom;
88
- if (!stateNode) return null;
89
- const node = stateNode;
90
-
91
- // Fabric: stateNode.canonical.publicInstance
92
- if (node.canonical?.publicInstance) {
93
- return node.canonical.publicInstance;
94
- }
95
-
96
- // Legacy Fabric: stateNode.canonical with measure
97
- if (node.canonical && typeof node.canonical.measure === "function") {
98
- return node.canonical;
99
- }
100
-
101
- // Legacy renderer: stateNode has measure directly
102
- if (typeof node.measure === "function") {
103
- return node;
104
- }
105
- return null;
106
- }
107
-
108
- /**
109
- * Get native tag from public instance or stateNode
110
- */
111
- function getNativeTag(instance) {
112
- const dom = getDOMNodeHandle(instance);
113
- if (dom !== null) return dom;
114
- if (instance == null) return null;
115
- const inst = instance;
116
-
117
- // Try direct properties
118
- if (inst.__nativeTag != null) return inst.__nativeTag;
119
- if (inst._nativeTag != null) return inst._nativeTag;
120
- if (inst.nativeTag != null) return inst.nativeTag;
121
-
122
- // Try canonical
123
- if (inst.canonical) {
124
- if (inst.canonical.__nativeTag != null) return inst.canonical.__nativeTag;
125
- if (inst.canonical._nativeTag != null) return inst.canonical._nativeTag;
126
- // Modern Fabric instance handles: { node, canonical: { nativeTag, ... } }.
127
- // Without this shape ~99% of traced nodes were dropped on New
128
- // Architecture — highlights only appeared for tap-shaped legacy nodes.
129
- if (inst.canonical.nativeTag != null) return inst.canonical.nativeTag;
130
- }
131
- return null;
132
- }
133
-
134
- /**
135
- * Extract component info from a stateNode for RenderTracker
136
- */
137
- function extractComponentInfo(stateNode) {
138
- const node = stateNode;
139
- const info = {
140
- viewType: "Unknown"
141
- };
142
-
143
- // Get viewType from viewConfig
144
- if (node?.canonical?.viewConfig?.uiViewClassName) {
145
- info.viewType = node.canonical.viewConfig.uiViewClassName;
146
- } else if (node?.viewConfig?.uiViewClassName) {
147
- info.viewType = node.viewConfig.uiViewClassName;
148
- }
149
-
150
- // Try to get props from various locations
151
- // Fabric: canonical.internalInstanceHandle, Paper: _internalInstanceHandle, RN CLI DEV: _internalFiberInstanceHandleDEV
152
- const fiber = node?.canonical?.internalInstanceHandle || node?._internalInstanceHandle || node?._internalFiberInstanceHandleDEV || getDOMFiber(node);
153
- const currentProps = node?.canonical?.currentProps;
154
- const pendingProps = node?.canonical?.pendingProps;
155
- const fiberPendingProps = fiber?.pendingProps;
156
- const fiberMemoizedProps = fiber?.memoizedProps;
157
-
158
- // Extract testID
159
- info.testID = currentProps?.testID || pendingProps?.testID || fiberPendingProps?.testID || fiberMemoizedProps?.testID || undefined;
160
-
161
- // Extract nativeID
162
- info.nativeID = currentProps?.nativeID || pendingProps?.nativeID || fiberPendingProps?.nativeID || fiberMemoizedProps?.nativeID || undefined;
163
-
164
- // Extract accessibilityLabel
165
- info.accessibilityLabel = currentProps?.accessibilityLabel || pendingProps?.accessibilityLabel || fiberPendingProps?.accessibilityLabel || fiberMemoizedProps?.accessibilityLabel || undefined;
166
-
167
- // Extract componentName - use getOwningComponentName to get the React component
168
- // that rendered this host component
169
- info.componentName = getOwningComponentName(fiber) || undefined;
170
- return info;
171
- }
172
-
173
- /**
174
- * Describe a node for logging (extensive version for debugging)
175
- */
176
- function describeNodeForLog(stateNode) {
177
- const node = stateNode;
178
- const publicInstance = getPublicInstance(stateNode);
179
- const nativeTag = getNativeTag(stateNode) || getNativeTag(publicInstance);
180
- const info = {
181
- nativeTag: nativeTag ?? "unknown",
182
- type: node?.canonical ? "Fabric" : "Legacy",
183
- hasMeasure: typeof publicInstance?.measure === "function"
184
- };
185
-
186
- // Extract as much info as possible from the stateNode
187
- if (node) {
188
- // Direct properties on stateNode
189
- info.stateNodeKeys = Object.keys(node).slice(0, 20);
190
-
191
- // Check the 'node' property (might have useful info)
192
- if (node.node) {
193
- info.nodeKeys = Object.keys(node.node).slice(0, 20);
194
- }
195
-
196
- // Check for viewConfig (contains component type info)
197
- if (node.viewConfig) {
198
- info.viewConfig = {
199
- uiViewClassName: node.viewConfig.uiViewClassName,
200
- validAttributes: node.viewConfig.validAttributes ? Object.keys(node.viewConfig.validAttributes).slice(0, 10) : undefined
201
- };
202
- }
203
-
204
- // Check canonical structure (Fabric)
205
- if (node.canonical) {
206
- const canonical = node.canonical;
207
- info.canonicalKeys = Object.keys(canonical).slice(0, 20);
208
- if (canonical.viewConfig) {
209
- info.canonicalViewConfig = {
210
- uiViewClassName: canonical.viewConfig.uiViewClassName
211
- };
212
- }
213
- if (canonical.nativeTag != null) {
214
- info.canonicalNativeTag = canonical.nativeTag;
215
- }
216
-
217
- // Check internalInstanceHandle (THE FIBER!)
218
- if (canonical.internalInstanceHandle) {
219
- const fiber = canonical.internalInstanceHandle;
220
- info.fiberKeys = Object.keys(fiber).slice(0, 30);
221
-
222
- // Component type info
223
- if (fiber.type) {
224
- info.fiberType = typeof fiber.type === "function" ? fiber.type.name || fiber.type.displayName || "function" : fiber.type;
225
- }
226
- if (fiber.elementType) {
227
- info.fiberElementType = typeof fiber.elementType === "function" ? fiber.elementType.name || fiber.elementType.displayName || "function" : fiber.elementType;
228
- }
229
-
230
- // Debug info on fiber
231
- if (fiber._debugOwner) {
232
- const owner = fiber._debugOwner;
233
- info.fiberDebugOwner = owner.type?.name || owner.type?.displayName || owner.elementType?.name || "unknown";
234
- }
235
- if (fiber._debugSource) {
236
- info.fiberDebugSource = fiber._debugSource;
237
- }
238
-
239
- // Fiber tag (tells us what kind of fiber it is)
240
- if (fiber.tag != null) {
241
- info.fiberTag = fiber.tag;
242
- }
243
-
244
- // pendingProps on fiber might have testID/nativeID
245
- if (fiber.pendingProps) {
246
- if (fiber.pendingProps.nativeID) info.fiberPendingNativeID = fiber.pendingProps.nativeID;
247
- if (fiber.pendingProps.testID) info.fiberPendingTestID = fiber.pendingProps.testID;
248
- }
249
- if (fiber.memoizedProps) {
250
- if (fiber.memoizedProps.nativeID) info.fiberMemoizedNativeID = fiber.memoizedProps.nativeID;
251
- if (fiber.memoizedProps.testID) info.fiberMemoizedTestID = fiber.memoizedProps.testID;
252
- }
253
- }
254
-
255
- // Check publicInstance
256
- if (canonical.publicInstance) {
257
- const pub = canonical.publicInstance;
258
- info.publicInstanceKeys = Object.keys(pub).slice(0, 20);
259
-
260
- // Look for nativeID
261
- if (pub.nativeID != null) info.nativeID = pub.nativeID;
262
- if (pub._nativeID != null) info._nativeID = pub._nativeID;
263
-
264
- // Look for props
265
- if (pub.props) {
266
- info.publicInstanceProps = Object.keys(pub.props).slice(0, 15);
267
- if (pub.props.nativeID) info.propsNativeID = pub.props.nativeID;
268
- if (pub.props.testID) info.propsTestID = pub.props.testID;
269
- if (pub.props.accessibilityLabel) info.accessibilityLabel = pub.props.accessibilityLabel;
270
- }
271
- }
272
-
273
- // Check for currentProps - log actual VALUES
274
- if (canonical.currentProps) {
275
- info.currentPropsKeys = Object.keys(canonical.currentProps).slice(0, 15);
276
- // Log actual values of identifying props
277
- if (canonical.currentProps.nativeID != null) info.currentPropsNativeID = canonical.currentProps.nativeID;
278
- if (canonical.currentProps.testID != null) info.currentPropsTestID = canonical.currentProps.testID;
279
- if (canonical.currentProps.accessibilityLabel != null) info.currentPropsAccessLabel = canonical.currentProps.accessibilityLabel;
280
- }
281
-
282
- // Check for pendingProps
283
- if (canonical.pendingProps) {
284
- info.pendingPropsKeys = Object.keys(canonical.pendingProps).slice(0, 15);
285
- if (canonical.pendingProps.nativeID != null) info.pendingPropsNativeID = canonical.pendingProps.nativeID;
286
- if (canonical.pendingProps.testID != null) info.pendingPropsTestID = canonical.pendingProps.testID;
287
- }
288
- }
289
-
290
- // Check for fiber reference directly on node
291
- if (node._debugOwner) {
292
- const owner = node._debugOwner;
293
- info.debugOwnerType = owner.type?.name || owner.type?.displayName || typeof owner.type;
294
- }
295
- if (node._debugSource) {
296
- info.debugSource = node._debugSource;
297
- }
298
- }
299
- return info;
300
- }
301
-
302
- // Set to true to enable debug logging
303
- const DEBUG_LOGGING = false;
304
-
305
- // Lock to prevent infinite loops when rendering our overlay
306
- let renderingLock = false;
307
- let renderingLockTimeout = null;
308
-
309
- // How long to ignore new events after starting a render (ms)
310
- // Should match HIGHLIGHT_DURATION in the overlay to prevent false triggers
311
- const RENDER_LOCK_DURATION = 350;
312
-
313
- // Track nativeTags of components we're currently highlighting
314
- // This helps us identify (and skip) our own overlay Views if they re-render
315
- const renderedOverlayTags = new Set();
316
-
317
- /**
318
- * Check if a nativeTag belongs to our overlay (was rendered by us previously)
319
- */
320
- function isOurOverlayTag(nativeTag) {
321
- if (nativeTag == null) return false;
322
- return renderedOverlayTags.has(nativeTag);
323
- }
324
-
325
- // ============================================================================
326
- // OPTIMIZED DEV TOOLS DETECTION
327
- // ============================================================================
328
- // Performance optimizations applied:
329
- // 1. Result caching by nativeTag (same tag = same result)
330
- // 2. Set-based O(1) lookups instead of multiple string comparisons
331
- // 3. Component name check FIRST (appears early in tree, ~depth 5-8)
332
- // 4. Early exit on first match
333
- // 5. Cached property access to avoid repeated traversal
334
- // ============================================================================
335
-
336
- // Component-name sets/prefixes live in devtoolsComponentNames.ts (shared with
337
- // CommitProfiler). Native-ID sets stay here — only the node walk uses them.
338
-
339
- // Native IDs that MUST always be excluded (highlight overlay)
340
- const HIGHLIGHT_OVERLAY_NATIVE_IDS = new Set(["highlight-updates-overlay", "__rn_buoy__highlight-modal"]);
341
-
342
- // Other dev tools native IDs - can be toggled
343
- const OTHER_DEV_TOOLS_NATIVE_IDS = new Set(["jsmodal-root", "image-overlay-standalone",
344
- // LogBox native IDs
345
- "logbox_inspector", "logbox"]);
346
-
347
- // Cache: nativeTag -> isDevTools (avoid re-walking tree for same node)
348
- const devToolsNodeCache = new Map();
349
- const CACHE_MAX_SIZE = 500;
350
-
351
- /**
352
- * Clear the devtools node cache.
353
- * Call this when the excludeDevTools setting changes to re-evaluate all nodes.
354
- */
355
- function clearDevToolsCache() {
356
- devToolsNodeCache.clear();
357
- }
358
-
359
- /**
360
- * Check if a nativeID belongs to highlight overlay (always excluded)
361
- */
362
- function isHighlightOverlayNativeID(nativeID) {
363
- if (!nativeID) return false;
364
- // Direct Set lookup (O(1))
365
- if (HIGHLIGHT_OVERLAY_NATIVE_IDS.has(nativeID)) return true;
366
- // Prefix check for highlight overlay
367
- if (nativeID.startsWith("__highlight_")) return true;
368
- return false;
369
- }
370
-
371
- /**
372
- * Check if a nativeID belongs to other dev tools (optionally excluded)
373
- */
374
- function isOtherDevToolsNativeID(nativeID) {
375
- if (!nativeID) return false;
376
- // Direct Set lookup (O(1))
377
- if (OTHER_DEV_TOOLS_NATIVE_IDS.has(nativeID)) return true;
378
- // Prefix checks for other devtools nativeIDs
379
- const firstChar = nativeID.charCodeAt(0);
380
- if (firstChar === 95) {
381
- // '_' = 95
382
- if (nativeID.startsWith("__rn_buoy__")) return true;
383
- }
384
- // Check for LogBox nativeIDs (start with 'l')
385
- if (firstChar === 108 && nativeID.startsWith("logbox")) {
386
- // 'l' = 108
387
- return true;
388
- }
389
- return false;
390
- }
391
-
392
- /**
393
- * Get component name from fiber (cached property access pattern)
394
- * For host components (RCTView, RCTText), returns the native type.
395
- * Use getOwningComponentName to get the React component that rendered it.
396
- */
397
- function getComponentName(fiber) {
398
- if (!fiber) return null;
399
- // Most common: type.name
400
- const type = fiber.type;
401
- if (type) {
402
- if (typeof type === 'string') return type;
403
- if (type.name) return type.name;
404
- if (type.displayName) return type.displayName;
405
- }
406
- // Fallback: elementType
407
- const elementType = fiber.elementType;
408
- if (elementType) {
409
- if (elementType.name) return elementType.name;
410
- if (elementType.displayName) return elementType.displayName;
411
- }
412
- return null;
413
- }
414
-
415
- // Common React Native internal component names to skip when finding user components
416
- const INTERNAL_COMPONENT_NAMES = new Set([
417
- // React Native core
418
- 'View', 'Text', 'TextImpl', 'Image', 'ScrollView', 'FlatList', 'SectionList', 'TouchableOpacity', 'TouchableHighlight', 'TouchableWithoutFeedback', 'Pressable', 'TextInput', 'Switch', 'ActivityIndicator', 'Modal', 'StatusBar', 'KeyboardAvoidingView',
419
- // Animated components
420
- 'AnimatedComponent', 'AnimatedComponentWrapper',
421
- // React Navigation / Screens
422
- 'ScreenContainer', 'ScreenStack', 'Screen', 'ScreenContentWrapper',
423
- // SVG components
424
- 'Svg', 'G', 'Path', 'Rect', 'Circle', 'Line', 'Polygon', 'Polyline', 'Ellipse', 'Text as SVGText', 'TSpan', 'TextPath', 'Use', 'Symbol', 'Defs', 'ClipPath', 'LinearGradient', 'RadialGradient', 'Stop', 'Mask', 'Pattern', 'Image as SVGImage',
425
- // SafeArea
426
- 'SafeAreaProvider', 'SafeAreaView', 'SafeAreaListener',
427
- // Gesture Handler
428
- 'GestureHandlerRootView', 'GestureDetector',
429
- // Reanimated
430
- 'ReanimatedView', 'ReanimatedText', 'ReanimatedImage', 'ReanimatedScrollView',
431
- // Common wrapper names
432
- 'Fragment', 'Suspense', 'Provider', 'Consumer', 'Context', 'ForwardRef']);
433
-
434
- /**
435
- * Check if a component name is an internal/wrapper component that should be skipped
436
- */
437
- function isInternalComponent(name) {
438
- if (!name) return true;
439
- if (INTERNAL_COMPONENT_NAMES.has(name)) return true;
440
- // Skip anonymous components and common patterns
441
- if (name === 'Unknown' || name === 'Component') return true;
442
- // Skip Animated.* wrappers
443
- if (name.startsWith('Animated')) return true;
444
- return false;
445
- }
446
-
447
- /**
448
- * Get the owning React component name for a host fiber.
449
- * Walks up the fiber tree to find the first user-defined component,
450
- * skipping React Native internal components.
451
- */
452
- function getOwningComponentName(fiber) {
453
- if (!fiber) return null;
454
-
455
- // Walk up the fiber tree looking for a user-defined component
456
- let current = fiber._debugOwner || fiber.return;
457
- let depth = 0;
458
- let firstNonHostName = null;
459
- while (current && depth < 30) {
460
- const name = getComponentName(current);
461
-
462
- // Skip host components (their type is a string like "RCTView")
463
- if (name && typeof current.type !== 'string') {
464
- // Remember the first non-host component as fallback
465
- if (!firstNonHostName) {
466
- firstNonHostName = name;
467
- }
468
- // Return this component if it's not an internal wrapper
469
- if (!isInternalComponent(name)) {
470
- return name;
471
- }
472
- }
473
- current = current.return;
474
- depth++;
475
- }
476
-
477
- // Fallback to first non-host component found (even if internal)
478
- return firstNonHostName;
479
- }
480
-
481
- /**
482
- * Check if a stateNode belongs to our dev tools.
483
- *
484
- * OPTIMIZED: Uses caching, O(1) Set lookups, and early exit patterns.
485
- * Walks up fiber tree checking component names (fast) before nativeIDs.
486
- *
487
- * When excludeDevTools setting is false, only the Highlight Updates overlay
488
- * is excluded (to prevent infinite loops). Other dev tools will be highlighted.
489
- */
490
- function isOurOverlayNode(stateNode) {
491
- const node = stateNode;
492
- // Fabric: fiber is at canonical.internalInstanceHandle
493
- // Paper/Legacy: fiber is at _internalInstanceHandle directly on stateNode
494
- // RN CLI DEV: fiber is at _internalFiberInstanceHandleDEV
495
- const fiber = node?.canonical?.internalInstanceHandle || node?._internalInstanceHandle || node?._internalFiberInstanceHandleDEV || getDOMFiber(node);
496
-
497
- // Get nativeTag for caching
498
- const nativeTag = getNativeTag(stateNode) || getNativeTag(node?.canonical?.publicInstance);
499
-
500
- // Check if we should exclude all dev tools or just highlight overlay.
501
- // Bench "profile our own tools" mode (the example app's /tool-bench page)
502
- // forces this OFF so live highlight boxes flash on our tool UI too —
503
- // except the perf-monitor HUD (checked separately in the walk below),
504
- // whose 250ms sample-tick churn would flash constantly. Cache reads and
505
- // writes are already gated on excludeDevTools, so bench mode bypasses
506
- // the cache and can't poison it.
507
- const benchMode = isCapturingBuoyToolRenders();
508
- const excludeDevTools = !benchMode && RenderTracker.getSettings().excludeDevTools;
509
- if (excludeDevTools && isDOMElement(stateNode) && stateNode.closest('[data-buoy-root]')) return true;
510
-
511
- // Check cache first (O(1)) - but only for the current excludeDevTools setting
512
- // When excludeDevTools is false, skip cache to re-evaluate all nodes
513
- if (nativeTag != null && excludeDevTools) {
514
- const cached = devToolsNodeCache.get(nativeTag);
515
- if (cached !== undefined) {
516
- return cached;
517
- }
518
- }
519
- let result = false;
520
-
521
- // Fast path: check direct nativeID
522
- const directNativeID = fiber?.pendingProps?.nativeID || fiber?.memoizedProps?.nativeID || node?.canonical?.currentProps?.nativeID || null;
523
-
524
- // Always check highlight overlay nativeIDs first (must always be excluded)
525
- if (isHighlightOverlayNativeID(directNativeID)) {
526
- result = true;
527
- } else if (excludeDevTools && isOtherDevToolsNativeID(directNativeID)) {
528
- // Only check other dev tools if excludeDevTools is enabled
529
- result = true;
530
- }
531
- if (!result && fiber) {
532
- // Walk up fiber tree - check component names FIRST (they appear early)
533
- let current = fiber;
534
- let depth = 0;
535
-
536
- // Reduced max depth - component names appear by depth 15 typically
537
- while (current && depth < 30) {
538
- // Component name check FIRST (faster, appears earlier in tree)
539
- const name = getComponentName(current);
540
- if (name) {
541
- // Always check highlight overlay components (must always be excluded)
542
- if (HIGHLIGHT_OVERLAY_COMPONENTS.has(name)) {
543
- result = true;
544
- break;
545
- }
546
- // Check highlight overlay prefixes
547
- for (const prefix of HIGHLIGHT_OVERLAY_PREFIXES) {
548
- if (name.startsWith(prefix)) {
549
- result = true;
550
- break;
551
- }
552
- }
553
- if (result) break;
554
-
555
- // Bench mode: the perf-monitor HUD still never flashes.
556
- if (benchMode && isPerfMonitorComponentName(name)) {
557
- result = true;
558
- break;
559
- }
560
-
561
- // Only check other dev tools if excludeDevTools is enabled
562
- if (excludeDevTools) {
563
- // Two sets, same meaning: COMPONENTS is the original list, EXACT
564
- // holds the names that used to be matched by over-broad prefixes
565
- // (the "Virtualized" that hid every FlatList, the "Dial" that hid
566
- // every Dialog). Both paths must consult both, or Buoy's own chrome
567
- // starts flashing highlight boxes in one of them and not the other.
568
- if (OTHER_DEV_TOOLS_COMPONENTS.has(name) || OTHER_DEV_TOOLS_EXACT.has(name)) {
569
- result = true;
570
- break;
571
- }
572
- // Check other dev tools prefixes
573
- for (const prefix of OTHER_DEV_TOOLS_PREFIXES) {
574
- if (name.startsWith(prefix)) {
575
- result = true;
576
- break;
577
- }
578
- }
579
- if (result) break;
580
- }
581
- }
582
-
583
- // NativeID check (only if component name didn't match)
584
- const nativeID = current.pendingProps?.nativeID || current.memoizedProps?.nativeID;
585
- if (isHighlightOverlayNativeID(nativeID)) {
586
- result = true;
587
- break;
588
- }
589
- if (excludeDevTools && isOtherDevToolsNativeID(nativeID)) {
590
- result = true;
591
- break;
592
- }
593
- current = current.return;
594
- depth++;
595
- }
596
- }
597
-
598
- // Only cache positive results when excludeDevTools is true (default mode)
599
- // Don't cache when excludeDevTools is false to avoid complex cache invalidation
600
- if (result && nativeTag != null && excludeDevTools) {
601
- if (devToolsNodeCache.size >= CACHE_MAX_SIZE) {
602
- // Clear oldest entries (simple strategy - clear half)
603
- const entries = Array.from(devToolsNodeCache.keys());
604
- for (let i = 0; i < CACHE_MAX_SIZE / 2; i++) {
605
- devToolsNodeCache.delete(entries[i]);
606
- }
607
- }
608
- devToolsNodeCache.set(nativeTag, result);
609
- }
610
- return result;
611
- }
612
-
613
- /**
614
- * Get color based on render count (same algorithm as DevTools)
615
- * More renders = warmer color (cyan → yellow)
616
- */
617
- function getColorForRenderCount(count) {
618
- // Clamp to color array bounds
619
- const index = Math.min(count - 1, COLORS.length - 1);
620
- return COLORS[Math.max(0, index)];
621
- }
622
-
623
- /**
624
- * Handle traceUpdates event from DevTools backend
625
- * This is called with a Set of stateNodes that should be highlighted
626
- *
627
- * Strategy to prevent infinite loops:
628
- * 1. Use a rendering lock while rendering highlights
629
- * 2. Use an isProcessing flag to prevent concurrent processing
630
- * 3. If Chrome DevTools agent is available, use native overlay (faster, no React)
631
- * 4. Otherwise, use our React overlay with locks to prevent cascading renders
632
- */
633
- function handleTraceUpdates(nodes) {
634
- if (nodes.size === 0) {
635
- return;
636
- }
637
-
638
- // Skip if neither visual toggle nor background tracking is enabled
639
- if (!globalEnabled && !backgroundTrackingEnabled) {
640
- return;
641
- }
642
-
643
- // Skip processing when paused - don't count renders or show highlights
644
- const trackerState = RenderTracker.getState();
645
- if (trackerState.isPaused) {
646
- return;
647
- }
648
-
649
- // Mark event received for end-to-end timing
650
- if (PerformanceLogger.isEnabled()) {
651
- markEventReceived();
652
- }
653
-
654
- // Start performance timing
655
- const batchSize = RenderTracker.getBatchSize();
656
- const perfTimer = PerformanceLogger.startBatch(nodes.size, batchSize);
657
-
658
- // NOTE: Lock-based skipping disabled - relying on nativeID filtering instead
659
- // If nativeID filtering doesn't work, re-enable this:
660
- //
661
- // if (renderingLock || isProcessing) {
662
- // if (DEBUG_LOGGING) {
663
- // console.log(`[HighlightUpdates] SKIPPED - lock:${renderingLock} processing:${isProcessing}`);
664
- // }
665
- // return;
666
- // }
667
- // isProcessing = true;
668
-
669
- // Process nodes: track render counts and assign colors
670
- // Filter out our own overlay nodes to prevent infinite loop
671
- // Also apply user-defined filters to both overlay AND tracking
672
- const nodesToDraw = [];
673
- let skippedOverlayCount = 0;
674
- let skippedByFilterCount = 0;
675
- const hasActiveFilters = RenderTracker.hasActiveFilters();
676
- for (const stateNode of nodes) {
677
- if (stateNode && typeof stateNode === "object") {
678
- try {
679
- // Skip our own overlay nodes (identified by nativeID)
680
- if (isOurOverlayNode(stateNode)) {
681
- skippedOverlayCount++;
682
- continue;
683
- }
684
-
685
- // Get nativeTag for tracking render counts
686
- const publicInstance = getPublicInstance(stateNode);
687
- const nativeTag = getNativeTag(stateNode) || getNativeTag(publicInstance);
688
- if (nativeTag == null) {
689
- continue;
690
- }
691
-
692
- // Extract component info for filtering
693
- const componentInfo = extractComponentInfo(stateNode);
694
-
695
- // Apply user-defined filters - skip components that don't pass filters
696
- // This affects BOTH the overlay highlights AND the render list
697
- if (hasActiveFilters && !RenderTracker.passesFilters(componentInfo)) {
698
- skippedByFilterCount++;
699
- continue;
700
- }
701
-
702
- // Check if render counting is enabled
703
- const showRenderCount = RenderTracker.getSettings().showRenderCount;
704
- let newCount;
705
- let color;
706
- if (showRenderCount) {
707
- // Get current render count and increment (using nativeTag as stable key)
708
- const currentCount = nodeRenderCounts.get(nativeTag) || 0;
709
- newCount = currentCount + 1;
710
- nodeRenderCounts.set(nativeTag, newCount);
711
- // Assign color based on render count
712
- color = getColorForRenderCount(newCount);
713
- } else {
714
- // Skip counting - use fixed color and count of 0
715
- newCount = 0;
716
- color = COLORS[0]; // Use first color (cyan)
717
- }
718
- nodesToDraw.push({
719
- node: stateNode,
720
- color,
721
- count: newCount
722
- });
723
- } catch {
724
- // Skip nodes from custom renderers (e.g. React Native Skia) that have
725
- // non-standard stateNode structures
726
- }
727
- }
728
- }
729
-
730
- // Mark filtering phase complete (includes both overlay nodes and user-filtered nodes)
731
- perfTimer.markFilteringComplete(skippedOverlayCount + skippedByFilterCount, nodesToDraw.length);
732
-
733
- // Only log if there are real updates (not just overlay re-renders)
734
- if (nodesToDraw.length === 0) {
735
- // All nodes were overlay nodes - silently skip
736
- perfTimer.finish(); // Still log the batch even if empty
737
- return;
738
- }
739
-
740
- // Log actual component updates
741
- if (DEBUG_LOGGING) {
742
- console.log(`[HighlightUpdates] ${nodesToDraw.length} component(s) re-rendered`);
743
- }
744
-
745
- // NOTE: We prefer our React overlay for standalone operation.
746
- // The native overlay only works when Chrome DevTools profiler is actively enabled.
747
- // Uncomment below to use native overlay when available:
748
- //
749
- // const agent = hook?.reactDevtoolsAgent;
750
- // if (agent?.emit) {
751
- // if (DEBUG_LOGGING) {
752
- // console.log(`[HighlightUpdates] Using native overlay (agent available)`);
753
- // }
754
- // agent.emit("drawTraceUpdates", nodesToDraw);
755
- // isProcessing = false;
756
- // return;
757
- // }
758
-
759
- // Check if we should process - either we have a visual callback OR event callbacks
760
- const hasEventCallbacks = RenderTracker.getRenderEventCallbackCount() > 0;
761
- if (!highlightCallback && !hasEventCallbacks) {
762
- if (DEBUG_LOGGING) {
763
- console.log(`[HighlightUpdates] No highlightCallback and no event callbacks - skipping render`);
764
- }
765
- isProcessing = false;
766
- return;
767
- }
768
-
769
- // NOTE: Lock disabled - relying on nativeID filtering instead
770
-
771
- // Measure each node and call the highlight callback
772
- // Use batch size from RenderTracker settings (default: 150)
773
- // Note: batchSize already retrieved above for perfTimer
774
- perfTimer.markMeasurementStart();
775
- // Measure up to 4× batchSize: coalesced commits can exceed one batch and
776
- // the old hard slice silently never highlighted the same tail components.
777
- const measurePromises = nodesToDraw.slice(0, batchSize * 4).map(({
778
- node: stateNode,
779
- color,
780
- count
781
- }) => new Promise(resolve => {
782
- // RN silently never fires measure callbacks for detached nodes;
783
- // without this timeout one dead node hangs the whole batch's
784
- // Promise.all (no boxes, no tracking, counts still climb).
785
- let settled = false;
786
- const settle = value => {
787
- if (settled) return;
788
- settled = true;
789
- clearTimeout(timeoutId);
790
- resolve(value);
791
- };
792
- const timeoutId = setTimeout(() => settle({
793
- rect: null,
794
- stateNode,
795
- color,
796
- count
797
- }), 500);
798
- const publicInstance = getPublicInstance(stateNode);
799
- const nativeTag = getNativeTag(stateNode) || getNativeTag(publicInstance);
800
- if (nativeTag == null) {
801
- settle({
802
- rect: null,
803
- stateNode,
804
- color,
805
- count
806
- });
807
- return;
808
- }
809
- const onMeasured = (x, y, width, height, pageX, pageY) => {
810
- if (pageX == null || pageY == null || width == null || height == null) {
811
- settle({
812
- rect: null,
813
- stateNode,
814
- color,
815
- count
816
- });
817
- return;
818
- }
819
- settle({
820
- rect: {
821
- id: nativeTag,
822
- x: pageX,
823
- y: pageY,
824
- width,
825
- height,
826
- color,
827
- count
828
- },
829
- stateNode,
830
- color,
831
- count
832
- });
833
- };
834
- if (!publicInstance) {
835
- // New Architecture: canonical.publicInstance is often lazily
836
- // ABSENT on traceUpdates wrappers — measure the wrapper's `node`
837
- // (the Fabric shadow node) directly through FabricUIManager.
838
- const fabricNode = stateNode.node;
839
- const fabricUI = globalThis.nativeFabricUIManager;
840
- if (fabricNode && fabricUI?.measure) {
841
- try {
842
- fabricUI.measure(fabricNode, onMeasured);
843
- } catch (error) {
844
- settle({
845
- rect: null,
846
- stateNode,
847
- color,
848
- count
849
- });
850
- }
851
- return;
852
- }
853
- settle({
854
- rect: null,
855
- stateNode,
856
- color,
857
- count
858
- });
859
- return;
860
- }
861
- try {
862
- publicInstance.measure(onMeasured);
863
- } catch (error) {
864
- settle({
865
- rect: null,
866
- stateNode,
867
- color,
868
- count
869
- });
870
- }
871
- }));
872
- Promise.all(measurePromises).then(results => {
873
- const validResults = results.filter(r => r.rect !== null);
874
- const rects = validResults.map(r => r.rect);
875
-
876
- // Mark measurement phase complete
877
- perfTimer.markMeasurementComplete(validResults.length, results.length - validResults.length);
878
-
879
- // DRAW FIRST. With the render list open, tracking a big burst
880
- // (store writes + cause detection + list row rebuilds) used to run
881
- // BEFORE the highlight callback, so boxes painted ~0.7s later
882
- // (user-timed: 1.3s list-closed vs 2s+ list-open, 2026-07-08).
883
- // Boxes are the product — paint them, then bookkeep.
884
- if (rects.length > 0 && highlightCallback && globalEnabled && !highlightsSuppressed) {
885
- highlightCallback(rects);
886
- }
887
-
888
- // Tracking/list work runs in a macrotask so React commits the boxes
889
- // before this heavier pass starts.
890
- setTimeout(() => {
891
- // Keep a live handle to each measured node so the desktop's "capture this
892
- // component" flow can re-measure (and scroll to) it on demand later.
893
- // Defensive: never let registration break the measurement/tracking batch.
894
- try {
895
- for (const r of validResults) {
896
- if (r.rect) registerTrackedNode(r.rect.id, r.stateNode);
897
- }
898
- } catch (e) {
899
- debugLog("registerTrackedNode batch failed", e);
900
- }
901
-
902
- // Track renders - behavior differs based on what's enabled:
903
- // - globalEnabled (visual tool): full tracking with storage and list updates
904
- // - backgroundTrackingEnabled only (Events tool): emit events only, no storage
905
- const settings = RenderTracker.getSettings();
906
- const trackCauses = settings.trackRenderCauses && settings.showRenderCount;
907
- let batchNativeTags = null;
908
- if (trackCauses) {
909
- batchNativeTags = new Set();
910
- for (const {
911
- rect
912
- } of validResults) {
913
- if (rect) {
914
- batchNativeTags.add(rect.id);
915
- }
916
- }
917
- }
918
- if (globalEnabled) {
919
- // Visual tool is on - full tracking with storage and list notifications
920
- RenderTracker.startBatch();
921
- for (const {
922
- rect,
923
- stateNode,
924
- color,
925
- count
926
- } of validResults) {
927
- if (rect) {
928
- const componentInfo = extractComponentInfo(stateNode);
929
- let renderCause;
930
- if (trackCauses && batchNativeTags) {
931
- const node = stateNode;
932
- const fiber = getFiberFromNode(node);
933
- renderCause = detectRenderCause(rect.id, fiber, batchNativeTags, settings.debugLogLevel);
934
- }
935
- RenderTracker.trackRender({
936
- nativeTag: rect.id,
937
- viewType: componentInfo.viewType,
938
- testID: componentInfo.testID,
939
- nativeID: componentInfo.nativeID,
940
- accessibilityLabel: componentInfo.accessibilityLabel,
941
- componentName: componentInfo.componentName,
942
- measurements: {
943
- x: rect.x,
944
- y: rect.y,
945
- width: rect.width,
946
- height: rect.height
947
- },
948
- color,
949
- count,
950
- renderCause
951
- });
952
- }
953
- }
954
- RenderTracker.endBatch();
955
- } else {
956
- // Only background tracking (Events tool) - emit events without storage
957
- for (const {
958
- rect,
959
- stateNode,
960
- color,
961
- count
962
- } of validResults) {
963
- if (rect) {
964
- const componentInfo = extractComponentInfo(stateNode);
965
- let renderCause;
966
- if (trackCauses && batchNativeTags) {
967
- const node = stateNode;
968
- const fiber = getFiberFromNode(node);
969
- renderCause = detectRenderCause(rect.id, fiber, batchNativeTags, settings.debugLogLevel);
970
- }
971
- RenderTracker.emitRenderEvent({
972
- nativeTag: rect.id,
973
- viewType: componentInfo.viewType,
974
- testID: componentInfo.testID,
975
- nativeID: componentInfo.nativeID,
976
- accessibilityLabel: componentInfo.accessibilityLabel,
977
- componentName: componentInfo.componentName,
978
- measurements: {
979
- x: rect.x,
980
- y: rect.y,
981
- width: rect.width,
982
- height: rect.height
983
- },
984
- color,
985
- count,
986
- renderCause
987
- });
988
- }
989
- }
990
- }
991
-
992
- // Mark tracking phase complete
993
- perfTimer.markTrackingComplete();
994
-
995
- // Mark callback phase complete and finish timing
996
- perfTimer.markCallbackComplete();
997
- perfTimer.finish();
998
- }, 0);
999
- }).catch(error => {
1000
- console.error("[HighlightUpdates] Error in measurement pipeline:", error);
1001
- perfTimer.finish(); // Still log timing even on error
1002
- });
1003
- }
1004
-
1005
- /* ================================================================== *
1006
- * Component locator — powers the desktop "screenshot this component"
1007
- * flow. The dashboard sends a query (testID / nativeID / name / nativeTag);
1008
- * we resolve it to a live native node, best-effort scroll it into view,
1009
- * re-measure its on-screen rectangle, and return that (plus the pixel scale
1010
- * and screen size) so the desktop can crop the simulator screenshot to it.
1011
- * ================================================================== */
1012
-
1013
- // nativeTag → live node, weakly held (when WeakRef exists in the runtime) so
1014
- // unmounted views can still be GC'd. WeakRef isn't in this package's TS lib, so
1015
- // reach it through globalThis rather than the (untyped) global.
1016
- const WeakRefCtor = globalThis.WeakRef;
1017
- const nodeRegistry = new Map();
1018
- function registerTrackedNode(nativeTag, stateNode) {
1019
- // WeakRef throws if the target isn't an object, so guard hard — this runs in
1020
- // the measure pipeline and must never break tracking.
1021
- if (nativeTag == null || stateNode == null || typeof stateNode !== "object") {
1022
- return;
1023
- }
1024
- try {
1025
- nodeRegistry.set(nativeTag, WeakRefCtor ? new WeakRefCtor(stateNode) : {
1026
- deref: () => stateNode
1027
- });
1028
- } catch {
1029
- nodeRegistry.set(nativeTag, {
1030
- deref: () => stateNode
1031
- });
1032
- }
1033
- }
1034
- function derefNode(nativeTag) {
1035
- const ref = nodeRegistry.get(nativeTag);
1036
- const node = ref?.deref();
1037
- if (!node) nodeRegistry.delete(nativeTag);
1038
- return node ?? null;
1039
- }
1040
-
1041
- /** Promisified absolute measure → on-screen rect in points (or null). */
1042
- function measureNode(publicInstance) {
1043
- return new Promise(resolve => {
1044
- try {
1045
- publicInstance.measure((_x, _y, width, height, pageX, pageY) => {
1046
- if (pageX == null || pageY == null || width == null || height == null) {
1047
- resolve(null);
1048
- } else {
1049
- resolve({
1050
- x: pageX,
1051
- y: pageY,
1052
- width,
1053
- height
1054
- });
1055
- }
1056
- });
1057
- } catch {
1058
- resolve(null);
1059
- }
1060
- });
1061
- }
1062
- function getFiberFromNode(stateNode) {
1063
- const node = stateNode;
1064
- return node?.canonical?.internalInstanceHandle || node?._internalInstanceHandle || node?._internalFiberInstanceHandleDEV || getDOMFiber(node) || null;
1065
- }
1066
-
1067
- /**
1068
- * Walk up the fiber tree from a node to find the nearest ScrollView-like
1069
- * instance (anything exposing scrollTo + an inner content node).
1070
- */
1071
- function findScrollAncestor(stateNode) {
1072
- let fiber = getFiberFromNode(stateNode);
1073
- let guard = 0;
1074
- while (fiber && guard++ < 200) {
1075
- const inst = fiber.stateNode;
1076
- if (inst && typeof inst.scrollTo === "function") {
1077
- // getInnerViewNode()/getScrollableNode() return a numeric node handle —
1078
- // only valid for the legacy UIManager.measureLayout fallback below.
1079
- // Fabric's ref.measureLayout requires an actual host-component ref
1080
- // (getNativeScrollRef()); passing it a number trips a dev warning
1081
- // ("ref.measureLayout must be called with a ref to a native component")
1082
- // and silently resolves neither callback.
1083
- const nativeRef = typeof inst.getNativeScrollRef === "function" && inst.getNativeScrollRef() || null;
1084
- const innerNode = typeof inst.getInnerViewNode === "function" && inst.getInnerViewNode() || typeof inst.getScrollableNode === "function" && inst.getScrollableNode() || inst;
1085
- return {
1086
- instance: inst,
1087
- nativeRef,
1088
- innerNode
1089
- };
1090
- }
1091
- fiber = fiber.return;
1092
- }
1093
- return null;
1094
- }
1095
-
1096
- /**
1097
- * Best-effort scroll of an ancestor ScrollView so the target sits near the top
1098
- * of its viewport. Returns true only if a scroll was actually issued. Never
1099
- * throws — if anything is missing (no ScrollView, measureLayout unsupported)
1100
- * it quietly returns false and the caller measures wherever the node is.
1101
- */
1102
- async function scrollDescendantIntoView(stateNode, publicInstance, margin) {
1103
- try {
1104
- const ancestor = findScrollAncestor(stateNode);
1105
- if (!ancestor) return false;
1106
-
1107
- // Position of the target WITHIN the scroll content — independent of the
1108
- // current scroll offset (the standard RN keyboard-aware-scroll technique).
1109
- // Try the Fabric path (ref.measureLayout against the inner view instance)
1110
- // first, then fall back to the legacy UIManager.measureLayout with tags.
1111
- const inst = publicInstance;
1112
- let top = null;
1113
-
1114
- // On some architectures measureLayout invokes NEITHER callback, which would
1115
- // hang the await forever — always race it against a short timeout.
1116
- const withTimeout = run => new Promise(resolve => {
1117
- let done = false;
1118
- const settle = v => {
1119
- if (done) return;
1120
- done = true;
1121
- resolve(v);
1122
- };
1123
- const timer = setTimeout(() => settle(null), 600);
1124
- try {
1125
- run(v => {
1126
- clearTimeout(timer);
1127
- settle(v);
1128
- });
1129
- } catch {
1130
- clearTimeout(timer);
1131
- settle(null);
1132
- }
1133
- });
1134
- if (ancestor.nativeRef && typeof inst.measureLayout === "function") {
1135
- top = await withTimeout(resolve => inst.measureLayout(ancestor.nativeRef, (_left, t) => resolve(t), () => resolve(null)));
1136
- }
1137
- if (top == null) {
1138
- const targetHandle = findNodeHandle(publicInstance);
1139
- const innerHandle = typeof ancestor.innerNode === "number" ? ancestor.innerNode : findNodeHandle(ancestor.innerNode);
1140
- if (targetHandle != null && innerHandle != null) {
1141
- top = await withTimeout(resolve => UIManager.measureLayout(targetHandle, innerHandle, () => resolve(null), (_left, t) => resolve(t)));
1142
- }
1143
- }
1144
- if (top == null) return false;
1145
- ancestor.instance.scrollTo({
1146
- y: Math.max(0, top - margin),
1147
- animated: false
1148
- });
1149
- // Let the scroll + layout settle before the caller re-measures.
1150
- await new Promise(r => setTimeout(r, 80));
1151
- return true;
1152
- } catch {
1153
- return false;
1154
- }
1155
- }
1156
- function matchScore(r, q) {
1157
- const fields = [r.testID, r.nativeID, r.accessibilityLabel, r.componentName, r.viewType, String(r.nativeTag)];
1158
- let best = 0;
1159
- for (const f of fields) {
1160
- if (!f) continue;
1161
- const lower = f.toLowerCase();
1162
- if (lower === q) return 3; // exact wins outright
1163
- if (lower.startsWith(q)) best = Math.max(best, 2);else if (lower.includes(q)) best = Math.max(best, 1);
1164
- }
1165
- return best;
1166
- }
1167
-
1168
- /**
1169
- * Resolve a component query to a fresh on-screen rectangle. See
1170
- * LocateComponentResult for the shape. Always resolves (never rejects).
1171
- */
1172
- async function locateComponent(params) {
1173
- const scrollIntoView = params.scrollIntoView !== false;
1174
- const margin = typeof params.margin === "number" ? params.margin : 12;
1175
- const renders = RenderTracker.getRenders();
1176
- const locateFromScreen = async () => {
1177
- const described = await describeScreen();
1178
- const q = (params.query ?? "").trim().toLowerCase();
1179
- let best;
1180
- for (const el of described.elements) {
1181
- if (params.nativeTag != null && el.nativeTag === params.nativeTag) {
1182
- best = {
1183
- el,
1184
- score: 1000
1185
- };
1186
- break;
1187
- }
1188
- const score = scoreTapMatch({
1189
- nativeTag: el.nativeTag,
1190
- testID: el.testID,
1191
- label: el.label,
1192
- text: el.text,
1193
- name: el.name,
1194
- tap: el.tap
1195
- }, {
1196
- query: q || undefined,
1197
- nativeTag: params.nativeTag
1198
- });
1199
- if (score <= 0) continue;
1200
- if (!best || score > best.score) best = {
1201
- el,
1202
- score
1203
- };
1204
- }
1205
- if (!best?.el.frame) {
1206
- return {
1207
- matched: false,
1208
- reason: "no-match",
1209
- candidates: []
1210
- };
1211
- }
1212
- const win = described.screen;
1213
- const f = best.el.frame;
1214
- return {
1215
- matched: true,
1216
- live: true,
1217
- rect: {
1218
- x: f.x * win.width,
1219
- y: f.y * win.height,
1220
- width: f.width * win.width,
1221
- height: f.height * win.height
1222
- },
1223
- scale: PixelRatio.get(),
1224
- screen: {
1225
- width: win.width,
1226
- height: win.height
1227
- },
1228
- nativeTag: best.el.nativeTag ?? undefined,
1229
- componentName: best.el.name,
1230
- testID: best.el.testID
1231
- };
1232
- };
1233
- if (renders.length === 0) return locateFromScreen();
1234
-
1235
- // Rank candidates (skip ranking when an explicit nativeTag was given).
1236
- const q = (params.query ?? "").trim().toLowerCase();
1237
- const ranked = q ? renders.map(r => ({
1238
- r,
1239
- score: matchScore(r, q)
1240
- })).filter(x => x.score > 0).sort((a, b) => b.score - a.score || b.r.lastRenderTime - a.r.lastRenderTime) : [];
1241
- const candidates = ranked.slice(0, 8).map(({
1242
- r
1243
- }) => ({
1244
- nativeTag: r.nativeTag,
1245
- componentName: r.componentName,
1246
- testID: r.testID,
1247
- nativeID: r.nativeID,
1248
- viewType: r.viewType,
1249
- renderCount: r.renderCount
1250
- }));
1251
- const targetTag = params.nativeTag ?? (ranked.length > 0 ? ranked[0].r.nativeTag : undefined);
1252
- if (targetTag == null) {
1253
- const located = await locateFromScreen();
1254
- return located.matched ? located : {
1255
- matched: false,
1256
- reason: "no-match",
1257
- candidates
1258
- };
1259
- }
1260
- const tracked = renders.find(r => r.nativeTag === targetTag);
1261
-
1262
- // Try a live re-measure (and scroll) using the registered node.
1263
- let rect = null;
1264
- let live = false;
1265
- let scrolled = false;
1266
- const node = derefNode(targetTag);
1267
- if (node) {
1268
- const publicInstance = getPublicInstance(node);
1269
- if (publicInstance) {
1270
- if (scrollIntoView) {
1271
- scrolled = await scrollDescendantIntoView(node, publicInstance, margin);
1272
- }
1273
- rect = await measureNode(publicInstance);
1274
- live = !!rect;
1275
- }
1276
- }
1277
-
1278
- // Fall back to the last synced measurement if the live path failed.
1279
- if (!rect && tracked?.measurements) {
1280
- rect = {
1281
- ...tracked.measurements
1282
- };
1283
- }
1284
- if (!rect) {
1285
- return {
1286
- matched: false,
1287
- reason: "no-measurement",
1288
- nativeTag: targetTag,
1289
- candidates
1290
- };
1291
- }
1292
- const scale = PixelRatio.get();
1293
- const win = Dimensions.get("window");
1294
- const inView = rect.x >= -1 && rect.y >= -1 && rect.x + rect.width <= win.width + 1 && rect.y + rect.height <= win.height + 1;
1295
- return {
1296
- matched: true,
1297
- live,
1298
- scrolled,
1299
- inView,
1300
- rect,
1301
- scale,
1302
- screen: {
1303
- width: win.width,
1304
- height: win.height
1305
- },
1306
- nativeTag: targetTag,
1307
- componentName: tracked?.componentName,
1308
- testID: tracked?.testID,
1309
- candidates
1310
- };
1311
- }
1312
-
1313
- /**
1314
- * Enable or disable trace updates on all renderer interfaces.
1315
- * This is the key function that makes standalone tracing work!
1316
- *
1317
- * The rendererInterfaces map contains the renderer backend for each React root.
1318
- * Each renderer has a setTraceUpdatesEnabled function that controls whether
1319
- * it emits 'traceUpdates' events when components re-render.
1320
- *
1321
- * See: react-devtools-core/dist/backend.js line 15487-15489
1322
- */
1323
- function setTraceUpdatesOnRenderers(enabled) {
1324
- if (!hook?.rendererInterfaces) {
1325
- debugLog("No rendererInterfaces available");
1326
- return;
1327
- }
1328
- let count = 0;
1329
- hook.rendererInterfaces.forEach((rendererInterface, rendererId) => {
1330
- if (typeof rendererInterface.setTraceUpdatesEnabled === "function") {
1331
- try {
1332
- rendererInterface.setTraceUpdatesEnabled(enabled);
1333
- count++;
1334
- debugLog(`Renderer ${rendererId}: setTraceUpdatesEnabled(${enabled})`);
1335
- } catch (error) {
1336
- debugLog(`Renderer ${rendererId}: error setting trace updates`, error);
1337
- }
1338
- } else {
1339
- debugLog(`Renderer ${rendererId}: no setTraceUpdatesEnabled method`);
1340
- }
1341
- });
1342
- debugLog(`Set trace updates ${enabled ? "enabled" : "disabled"} on ${count} renderer(s)`);
1343
-
1344
- // Also try the agent if available (in case DevTools is connected)
1345
- if (hook.reactDevtoolsAgent?.setTraceUpdatesEnabled) {
1346
- try {
1347
- hook.reactDevtoolsAgent.setTraceUpdatesEnabled(enabled);
1348
- debugLog("Also set trace updates on agent");
1349
- } catch (error) {
1350
- debugLog("Error setting trace updates on agent", error);
1351
- }
1352
- }
1353
- }
1354
-
1355
- /**
1356
- * Subscribe to the traceUpdates event from the hook
1357
- */
1358
- function subscribeToTraceUpdates() {
1359
- if (!hook) return;
1360
- if (traceUpdatesUnsubscribe) return; // Already subscribed
1361
-
1362
- debugLog("Subscribing to traceUpdates event");
1363
-
1364
- // The hook uses EventEmitter pattern with 'sub' method
1365
- // See: react-devtools-core/dist/backend.js line 17526
1366
- // hook.sub('traceUpdates', agent.onTraceUpdates)
1367
- if (typeof hook.sub === "function") {
1368
- traceUpdatesUnsubscribe = hook.sub("traceUpdates", handleTraceUpdates);
1369
- debugLog("Subscribed using hook.sub()");
1370
- } else {
1371
- debugLog("hook.sub not available, traceUpdates may not work");
1372
- }
1373
-
1374
- // CRITICAL: Enable trace updates on all renderers
1375
- // Without this, the renderers won't emit traceUpdates events
1376
- setTraceUpdatesOnRenderers(true);
1377
- }
1378
-
1379
- /**
1380
- * Unsubscribe from the traceUpdates event
1381
- */
1382
- function unsubscribeFromTraceUpdates() {
1383
- // Disable trace updates on renderers first
1384
- setTraceUpdatesOnRenderers(false);
1385
- if (traceUpdatesUnsubscribe) {
1386
- traceUpdatesUnsubscribe();
1387
- traceUpdatesUnsubscribe = null;
1388
- debugLog("Unsubscribed from traceUpdates event");
1389
- }
1390
- }
1391
-
1392
- /**
1393
- * Set the callback for rendering highlights
1394
- */
1395
- function setHighlightCallback(callback) {
1396
- highlightCallback = callback;
1397
- debugLog(`Highlight callback ${callback ? "set" : "cleared"}`);
1398
- }
1399
-
1400
- /**
1401
- * Set the callback for when a badge is pressed.
1402
- * This is used to navigate to the detail view when a user taps a render count badge.
1403
- */
1404
- function setBadgePressCallback(callback) {
1405
- badgePressCallback = callback;
1406
- debugLog(`Badge press callback ${callback ? "set" : "cleared"}`);
1407
- }
1408
-
1409
- /**
1410
- * Get the current badge press callback.
1411
- * Used by the overlay to check if badge presses should be handled.
1412
- */
1413
- function getBadgePressCallback() {
1414
- return badgePressCallback;
1415
- }
1416
-
1417
- /**
1418
- * Handle a badge press event.
1419
- * Calls the registered callback with the nativeTag of the component.
1420
- */
1421
- function handleBadgePress(nativeTag) {
1422
- if (badgePressCallback) {
1423
- badgePressCallback(nativeTag);
1424
- }
1425
- }
1426
-
1427
- // Spotlight highlight state - for showing which component is being viewed in detail
1428
-
1429
- let spotlightCallback = null;
1430
- let currentSpotlightTag = null;
1431
-
1432
- /**
1433
- * Set the callback for spotlight highlighting.
1434
- * Used by the overlay to show a special highlight for the component being viewed.
1435
- */
1436
- function setSpotlightCallback(callback) {
1437
- spotlightCallback = callback;
1438
- // If there's an existing spotlight, notify the new callback
1439
- if (callback && currentSpotlightTag !== null) {
1440
- callback(currentSpotlightTag);
1441
- }
1442
- }
1443
-
1444
- /**
1445
- * Set a spotlight highlight on a specific component.
1446
- * This is used when viewing a component's detail to show which one it is.
1447
- */
1448
- function setSpotlight(nativeTag) {
1449
- if (remoteHandler) {
1450
- remoteHandler("setSpotlight", {
1451
- nativeTag
1452
- });
1453
- return;
1454
- }
1455
- currentSpotlightTag = nativeTag;
1456
- if (spotlightCallback) {
1457
- spotlightCallback(nativeTag);
1458
- }
1459
- }
1460
-
1461
- // ============================================================================
1462
- // REMOTE MIRROR MODE
1463
- // ============================================================================
1464
-
1465
- let remoteHandler = null;
1466
-
1467
- /**
1468
- * Remote mirror mode (desktop dashboard): while a handler is set, mutations
1469
- * (toggle/setEnabled/toggleFreeze/clearRenderCounts/setSpotlight) forward
1470
- * (method, params) to the synced device instead of touching the local React
1471
- * internals — the resulting state comes back via replaceRemoteState(). Pass
1472
- * null to restore local behavior.
1473
- */
1474
- function setRemoteHandler(handler) {
1475
- remoteHandler = handler;
1476
- }
1477
-
1478
- /**
1479
- * Mirror the synced device's enabled/frozen flags into the local listeners
1480
- * (so the modal's toggle buttons reflect the device). Never patches React
1481
- * internals — it only updates the flags the UI reads.
1482
- */
1483
- function replaceRemoteState(state) {
1484
- if (globalEnabled !== state.enabled) {
1485
- globalEnabled = state.enabled;
1486
- notifyStateListeners();
1487
- }
1488
- if (isFrozen !== state.frozen) {
1489
- isFrozen = state.frozen;
1490
- notifyFreezeListeners();
1491
- }
1492
- }
1493
-
1494
- /**
1495
- * Get the current spotlight nativeTag.
1496
- */
1497
- function getSpotlight() {
1498
- return currentSpotlightTag;
1499
- }
1500
- function notifyStateListeners() {
1501
- stateListeners.forEach(listener => {
1502
- try {
1503
- listener(globalEnabled);
1504
- } catch (error) {
1505
- console.error("[HighlightUpdates] Error in state listener:", error);
1506
- }
1507
- });
1508
- }
1509
- function subscribe(listener) {
1510
- stateListeners.add(listener);
1511
- listener(globalEnabled);
1512
- return () => {
1513
- stateListeners.delete(listener);
1514
- };
1515
- }
1516
- function initialize() {
1517
- if (typeof __DEV__ !== "undefined" && !__DEV__) {
1518
- debugLog("Only available in development builds");
1519
- return false;
1520
- }
1521
-
1522
- // Remote mirror mode: initialization (DevTools hook, fiber walking)
1523
- // belongs to the device — pretend success so callers proceed to the
1524
- // forwarded toggle.
1525
- if (remoteHandler) {
1526
- return true;
1527
- }
1528
- if (initialized) {
1529
- return true;
1530
- }
1531
- hook = window?.__REACT_DEVTOOLS_GLOBAL_HOOK__ || null;
1532
- if (!hook) {
1533
- debugLog("React DevTools hook not found");
1534
- return false;
1535
- }
1536
- debugLog("Hook found");
1537
- debugLog(`Hook has sub: ${typeof hook.sub === "function"}`);
1538
- debugLog(`Hook has on: ${typeof hook.on === "function"}`);
1539
- debugLog(`Hook has emit: ${typeof hook.emit === "function"}`);
1540
-
1541
- // Install profiler interceptor to capture what DevTools detects
1542
- // This allows us to compare profiler data with our detection
1543
- installProfilerInterceptor();
1544
-
1545
- // Comparison callback available for future use when we re-enable our implementation
1546
- // setComparisonCallback((profilerNodes: Set<unknown>) => {
1547
- // debugLog(`[COMPARISON] Profiler detected ${profilerNodes.size} nodes`);
1548
- // });
1549
-
1550
- if (hook.rendererInterfaces && hook.rendererInterfaces.size > 0) {
1551
- initialized = true;
1552
- debugLog(`Initialized with ${hook.rendererInterfaces.size} renderer(s)`);
1553
- exposeGlobally();
1554
- return true;
1555
- }
1556
-
1557
- // Wait for renderer to be available
1558
- const checkInterval = setInterval(() => {
1559
- if (hook?.rendererInterfaces && hook.rendererInterfaces.size > 0) {
1560
- clearInterval(checkInterval);
1561
- initialized = true;
1562
- debugLog(`Initialized with ${hook.rendererInterfaces.size} renderer(s) (delayed)`);
1563
- exposeGlobally();
1564
- }
1565
- }, 100);
1566
- setTimeout(() => clearInterval(checkInterval), 10000);
1567
- return false;
1568
- }
1569
- function exposeGlobally() {
1570
- if (typeof window !== "undefined") {
1571
- window.__HIGHLIGHT_UPDATES_CONTROLLER__ = {
1572
- enable,
1573
- disable,
1574
- toggle,
1575
- isEnabled,
1576
- setEnabled,
1577
- subscribe,
1578
- initialize,
1579
- destroy,
1580
- isInitialized: () => initialized,
1581
- setHighlightCallback
1582
- };
1583
- }
1584
- }
1585
- function enable() {
1586
- if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1587
- if (!initialized) {
1588
- initialize();
1589
- }
1590
-
1591
- // Enabling the VISUAL tool always means boxes should show — clear any
1592
- // suppression left over from a silent (screenshot-tool) session.
1593
- if (highlightsSuppressed) {
1594
- highlightsSuppressed = false;
1595
- }
1596
- if (globalEnabled) {
1597
- return;
1598
- }
1599
- debugLog("Enabling highlights");
1600
-
1601
- // Only subscribe if not already subscribed via background tracking
1602
- if (!backgroundTrackingEnabled) {
1603
- subscribeToTraceUpdates();
1604
- }
1605
-
1606
- // Start tracking renders
1607
- RenderTracker.start();
1608
-
1609
- // Note: profiler logging disabled for normal operation
1610
- // enableProfilerLogging();
1611
-
1612
- globalEnabled = true;
1613
- notifyStateListeners();
1614
- notifySubscriberCountChange('render');
1615
- }
1616
- function disable() {
1617
- if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1618
- if (!globalEnabled) {
1619
- return;
1620
- }
1621
- debugLog("Disabling highlights");
1622
-
1623
- // Clear any pending locks/state
1624
- renderingLock = false;
1625
- isProcessing = false;
1626
- if (renderingLockTimeout) {
1627
- clearTimeout(renderingLockTimeout);
1628
- renderingLockTimeout = null;
1629
- }
1630
- renderedOverlayTags.clear();
1631
- devToolsNodeCache.clear(); // Clear detection cache
1632
- clearRenderCauseState(); // Clear render cause state to prevent memory leaks
1633
-
1634
- // Freeze is a view state on a LIVE overlay, and the overlay is going away:
1635
- // the boxes it was holding open were just cleared with the tags above. Left
1636
- // latched it outlived the thing it froze — switch tracking off and back on
1637
- // and the button still read "Unfreeze frame" on a tool with nothing frozen,
1638
- // while new highlights (correctly) refused to fade.
1639
- if (isFrozen) {
1640
- isFrozen = false;
1641
- notifyFreezeListeners();
1642
- }
1643
-
1644
- // Only unsubscribe if background tracking doesn't need it
1645
- if (!backgroundTrackingEnabled) {
1646
- unsubscribeFromTraceUpdates();
1647
- }
1648
-
1649
- // Stop tracking renders
1650
- RenderTracker.stop();
1651
-
1652
- // Note: profiler logging disabled for normal operation
1653
- // disableProfilerLogging();
1654
-
1655
- globalEnabled = false;
1656
- notifyStateListeners();
1657
- notifySubscriberCountChange('render');
1658
- }
1659
-
1660
- /**
1661
- * Enable background render tracking (for Events tool).
1662
- * This enables render interception WITHOUT affecting the visual toggle state.
1663
- * The visual highlight toggle remains independent.
1664
- */
1665
- function enableBackgroundTracking() {
1666
- if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1667
- if (backgroundTrackingEnabled) {
1668
- return;
1669
- }
1670
- if (!initialized) {
1671
- initialize();
1672
- }
1673
- debugLog("Enabling background tracking");
1674
-
1675
- // Only subscribe if not already subscribed via main toggle
1676
- if (!globalEnabled) {
1677
- subscribeToTraceUpdates();
1678
- }
1679
- backgroundTrackingEnabled = true;
1680
- }
1681
-
1682
- /**
1683
- * Disable background render tracking (for Events tool).
1684
- * Only actually unsubscribes if the main toggle is also off.
1685
- */
1686
- function disableBackgroundTracking() {
1687
- if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1688
- if (!backgroundTrackingEnabled) {
1689
- return;
1690
- }
1691
- debugLog("Disabling background tracking");
1692
- backgroundTrackingEnabled = false;
1693
-
1694
- // Only unsubscribe if main toggle is also off
1695
- if (!globalEnabled) {
1696
- unsubscribeFromTraceUpdates();
1697
- }
1698
- }
1699
-
1700
- /**
1701
- * Check if background tracking is enabled (for debugging)
1702
- */
1703
- function isBackgroundTrackingEnabled() {
1704
- return backgroundTrackingEnabled;
1705
- }
1706
- function toggle() {
1707
- if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1708
- if (remoteHandler) {
1709
- remoteHandler("toggle");
1710
- return;
1711
- }
1712
- if (globalEnabled) {
1713
- disable();
1714
- } else {
1715
- enable();
1716
- }
1717
- }
1718
-
1719
- /**
1720
- * Clear all render counts and tracked data
1721
- */
1722
- function clearRenderCounts() {
1723
- if (remoteHandler) {
1724
- remoteHandler("clearRenderCounts");
1725
- return;
1726
- }
1727
- nodeRenderCounts.clear();
1728
- RenderTracker.clear();
1729
- debugLog("Cleared render counts");
1730
- }
1731
- function isEnabled() {
1732
- return globalEnabled;
1733
- }
1734
- function setEnabled(enabled) {
1735
- if (remoteHandler) {
1736
- remoteHandler("setEnabled", {
1737
- enabled
1738
- });
1739
- return;
1740
- }
1741
- if (enabled) enable();else disable();
1742
- }
1743
-
1744
- /**
1745
- * Suppress (or restore) the visual highlight boxes without affecting tracking.
1746
- * When suppressing, any boxes currently on screen are cleared immediately.
1747
- */
1748
- function setHighlightsSuppressed(suppressed) {
1749
- if (highlightsSuppressed === suppressed) return;
1750
- highlightsSuppressed = suppressed;
1751
- if (suppressed && highlightCallback) {
1752
- // Wipe whatever is currently drawn so nothing lingers.
1753
- highlightCallback([]);
1754
- }
1755
- }
1756
- function getHighlightsSuppressed() {
1757
- return highlightsSuppressed;
1758
- }
1759
-
1760
- /**
1761
- * Silent tracking — used by the desktop "screenshot this component" flow.
1762
- * Turns the render tracker on (so the render list + measurements populate and
1763
- * sync) while keeping the visual highlight boxes hidden. Disabling restores
1764
- * normal state. On the desktop mirror this forwards to the device.
1765
- */
1766
- function setSilentTracking(enabled) {
1767
- if (remoteHandler) {
1768
- remoteHandler("setSilentTracking", {
1769
- enabled
1770
- });
1771
- return;
1772
- }
1773
- if (enabled) {
1774
- enable(); // clears suppression as part of a visual enable...
1775
- setHighlightsSuppressed(true); // ...so re-suppress right after.
1776
- } else {
1777
- setHighlightsSuppressed(false);
1778
- disable();
1779
- }
1780
- }
1781
- function isInitialized() {
1782
- return initialized;
1783
- }
1784
-
1785
- // ============================================================================
1786
- // FREEZE FRAME MODE
1787
- // ============================================================================
1788
-
1789
- /**
1790
- * Notify all freeze state listeners of a change
1791
- */
1792
- function notifyFreezeListeners() {
1793
- freezeListeners.forEach(listener => {
1794
- try {
1795
- listener(isFrozen);
1796
- } catch (error) {
1797
- console.error("[HighlightUpdates] Error in freeze listener:", error);
1798
- }
1799
- });
1800
- }
1801
-
1802
- /**
1803
- * Subscribe to freeze state changes
1804
- */
1805
- function subscribeToFreeze(listener) {
1806
- freezeListeners.add(listener);
1807
- listener(isFrozen);
1808
- return () => {
1809
- freezeListeners.delete(listener);
1810
- };
1811
- }
1812
-
1813
- /**
1814
- * Freeze highlights - prevents highlights from fading away.
1815
- * New renders are still captured but old highlights don't clear.
1816
- */
1817
- function freeze() {
1818
- if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1819
- if (isFrozen) return;
1820
- isFrozen = true;
1821
- debugLog("Freeze mode enabled");
1822
- notifyFreezeListeners();
1823
- }
1824
-
1825
- /**
1826
- * Unfreeze highlights - resumes normal cleanup behavior.
1827
- * Clears all current highlights when unfreezing.
1828
- */
1829
- function unfreeze() {
1830
- if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1831
- if (!isFrozen) return;
1832
- isFrozen = false;
1833
- debugLog("Freeze mode disabled");
1834
-
1835
- // Clear all current highlights when unfreezing
1836
- if (highlightCallback) {
1837
- highlightCallback([]);
1838
- }
1839
- notifyFreezeListeners();
1840
- }
1841
-
1842
- /**
1843
- * Toggle freeze state
1844
- */
1845
- function toggleFreeze() {
1846
- if (remoteHandler) {
1847
- remoteHandler("toggleFreeze");
1848
- return;
1849
- }
1850
- if (isFrozen) {
1851
- unfreeze();
1852
- } else {
1853
- freeze();
1854
- }
1855
- }
1856
-
1857
- /**
1858
- * Check if freeze mode is active
1859
- */
1860
- function getFrozen() {
1861
- return isFrozen;
1862
- }
1863
- function destroy() {
1864
- if (!initialized) return;
1865
- unsubscribeFromTraceUpdates();
1866
-
1867
- // Uninstall profiler interceptor
1868
- uninstallProfilerInterceptor();
1869
- setComparisonCallback(null);
1870
-
1871
- // Reset freeze state
1872
- isFrozen = false;
1873
- freezeListeners.clear();
1874
- globalEnabled = false;
1875
- hook = null;
1876
- highlightCallback = null;
1877
- initialized = false;
1878
- if (typeof window !== "undefined") {
1879
- delete window.__HIGHLIGHT_UPDATES_CONTROLLER__;
1880
- }
1881
- debugLog("Destroyed");
1882
- }
1883
- const HighlightUpdatesController = {
1884
- subscribe,
1885
- enable,
1886
- disable,
1887
- toggle,
1888
- isEnabled,
1889
- setEnabled,
1890
- initialize,
1891
- destroy,
1892
- isInitialized,
1893
- setHighlightCallback,
1894
- clearRenderCounts,
1895
- // Freeze frame mode
1896
- freeze,
1897
- unfreeze,
1898
- toggleFreeze,
1899
- getFrozen,
1900
- subscribeToFreeze,
1901
- // Badge press callback for "Click Overlay Badge → Jump to Detail"
1902
- setBadgePressCallback,
1903
- getBadgePressCallback,
1904
- handleBadgePress,
1905
- // Spotlight highlight for detail view
1906
- setSpotlightCallback,
1907
- setSpotlight,
1908
- getSpotlight,
1909
- // Cache management for excludeDevTools toggle
1910
- clearDevToolsCache,
1911
- // Background tracking for Events tool (separate from visual toggle)
1912
- enableBackgroundTracking,
1913
- disableBackgroundTracking,
1914
- isBackgroundTrackingEnabled,
1915
- // Remote mirror mode (desktop dashboard)
1916
- setRemoteHandler,
1917
- replaceRemoteState,
1918
- // Component locator (desktop "screenshot this component" flow)
1919
- locateComponent,
1920
- // Silent tracking (track + measure without drawing boxes)
1921
- setHighlightsSuppressed,
1922
- getHighlightsSuppressed,
1923
- setSilentTracking
1924
- };
1925
- export default HighlightUpdatesController;
1
+ "use strict";import{getDOMFiber as W,getDOMNodeHandle as Se,getDOMPublicInstance as Ne,isDOMElement as Oe}from"@buoy-gg/shared-ui/utils";"use strict";import{installProfilerInterceptor as Le,uninstallProfilerInterceptor as Re,setComparisonCallback as He}from"./ProfilerInterceptor";import{findNodeHandle as ae,UIManager as Ve,Dimensions as ze,PixelRatio as oe}from"react-native";import{RenderTracker as v}from"./RenderTracker";import{describeScreen as xe}from"./screenElements";import{scoreTapMatch as Ue}from"./tapMatch";import{PerformanceLogger as se,markEventReceived as Ae}from"./PerformanceLogger";import{detectRenderCause as le,clearRenderCauseState as Fe}from"./RenderCauseDetector";import{notifySubscriberCountChange as ce}from"@buoy-gg/shared-ui";import{HIGHLIGHT_OVERLAY_COMPONENTS as Me,HIGHLIGHT_OVERLAY_PREFIXES as Ge,OTHER_DEV_TOOLS_COMPONENTS as Be,OTHER_DEV_TOOLS_EXACT as $e,OTHER_DEV_TOOLS_PREFIXES as je,isCapturingBuoyToolRenders as We,isPerfMonitorComponentName as Ke}from"./devtoolsComponentNames";let w=false;let V=false;let L=false;let N=false;let y=null;let O=null;let A=null;let z=null;let ue=false;let k=false;const F=new Set;const K=new Set;const q=new Map;const X=["#37afa9","#63b19e","#80b393","#97b488","#abb67d","#beb771","#cfb965","#dfba57","#efbb49","#febc38"];const qe=false;function u(e,n){if(!qe)return;if(n!==void 0){console.log(`[HighlightUpdates] ${e}`,n)}else{console.log(`[HighlightUpdates] ${e}`)}}function M(e){const n=Ne(e);if(n)return n;if(!e)return null;const r=e;if(r.canonical?.publicInstance){return r.canonical.publicInstance}if(r.canonical&&typeof r.canonical.measure==="function"){return r.canonical}if(typeof r.measure==="function"){return r}return null}function R(e){const n=Se(e);if(n!==null)return n;if(e==null)return null;const r=e;if(r.__nativeTag!=null)return r.__nativeTag;if(r._nativeTag!=null)return r._nativeTag;if(r.nativeTag!=null)return r.nativeTag;if(r.canonical){if(r.canonical.__nativeTag!=null)return r.canonical.__nativeTag;if(r.canonical._nativeTag!=null)return r.canonical._nativeTag;if(r.canonical.nativeTag!=null)return r.canonical.nativeTag}return null}function Y(e){const n=e;const r={viewType:"Unknown"};if(n?.canonical?.viewConfig?.uiViewClassName){r.viewType=n.canonical.viewConfig.uiViewClassName}else if(n?.viewConfig?.uiViewClassName){r.viewType=n.viewConfig.uiViewClassName}const o=n?.canonical?.internalInstanceHandle||n?._internalInstanceHandle||n?._internalFiberInstanceHandleDEV||W(n);const i=n?.canonical?.currentProps;const a=n?.canonical?.pendingProps;const t=o?.pendingProps;const f=o?.memoizedProps;r.testID=i?.testID||a?.testID||t?.testID||f?.testID||void 0;r.nativeID=i?.nativeID||a?.nativeID||t?.nativeID||f?.nativeID||void 0;r.accessibilityLabel=i?.accessibilityLabel||a?.accessibilityLabel||t?.accessibilityLabel||f?.accessibilityLabel||void 0;r.componentName=nn(o)||void 0;return r}function Gn(e){const n=e;const r=M(e);const o=R(e)||R(r);const i={nativeTag:o??"unknown",type:n?.canonical?"Fabric":"Legacy",hasMeasure:typeof r?.measure==="function"};if(n){i.stateNodeKeys=Object.keys(n).slice(0,20);if(n.node){i.nodeKeys=Object.keys(n.node).slice(0,20)}if(n.viewConfig){i.viewConfig={uiViewClassName:n.viewConfig.uiViewClassName,validAttributes:n.viewConfig.validAttributes?Object.keys(n.viewConfig.validAttributes).slice(0,10):void 0}}if(n.canonical){const a=n.canonical;i.canonicalKeys=Object.keys(a).slice(0,20);if(a.viewConfig){i.canonicalViewConfig={uiViewClassName:a.viewConfig.uiViewClassName}}if(a.nativeTag!=null){i.canonicalNativeTag=a.nativeTag}if(a.internalInstanceHandle){const t=a.internalInstanceHandle;i.fiberKeys=Object.keys(t).slice(0,30);if(t.type){i.fiberType=typeof t.type==="function"?t.type.name||t.type.displayName||"function":t.type}if(t.elementType){i.fiberElementType=typeof t.elementType==="function"?t.elementType.name||t.elementType.displayName||"function":t.elementType}if(t._debugOwner){const f=t._debugOwner;i.fiberDebugOwner=f.type?.name||f.type?.displayName||f.elementType?.name||"unknown"}if(t._debugSource){i.fiberDebugSource=t._debugSource}if(t.tag!=null){i.fiberTag=t.tag}if(t.pendingProps){if(t.pendingProps.nativeID)i.fiberPendingNativeID=t.pendingProps.nativeID;if(t.pendingProps.testID)i.fiberPendingTestID=t.pendingProps.testID}if(t.memoizedProps){if(t.memoizedProps.nativeID)i.fiberMemoizedNativeID=t.memoizedProps.nativeID;if(t.memoizedProps.testID)i.fiberMemoizedTestID=t.memoizedProps.testID}}if(a.publicInstance){const t=a.publicInstance;i.publicInstanceKeys=Object.keys(t).slice(0,20);if(t.nativeID!=null)i.nativeID=t.nativeID;if(t._nativeID!=null)i._nativeID=t._nativeID;if(t.props){i.publicInstanceProps=Object.keys(t.props).slice(0,15);if(t.props.nativeID)i.propsNativeID=t.props.nativeID;if(t.props.testID)i.propsTestID=t.props.testID;if(t.props.accessibilityLabel)i.accessibilityLabel=t.props.accessibilityLabel}}if(a.currentProps){i.currentPropsKeys=Object.keys(a.currentProps).slice(0,15);if(a.currentProps.nativeID!=null)i.currentPropsNativeID=a.currentProps.nativeID;if(a.currentProps.testID!=null)i.currentPropsTestID=a.currentProps.testID;if(a.currentProps.accessibilityLabel!=null)i.currentPropsAccessLabel=a.currentProps.accessibilityLabel}if(a.pendingProps){i.pendingPropsKeys=Object.keys(a.pendingProps).slice(0,15);if(a.pendingProps.nativeID!=null)i.pendingPropsNativeID=a.pendingProps.nativeID;if(a.pendingProps.testID!=null)i.pendingPropsTestID=a.pendingProps.testID}}if(n._debugOwner){const a=n._debugOwner;i.debugOwnerType=a.type?.name||a.type?.displayName||typeof a.type}if(n._debugSource){i.debugSource=n._debugSource}}return i}const fe=false;let Xe=false;let Z=null;const Bn=350;const de=new Set;function $n(e){if(e==null)return false;return de.has(e)}const Ye=new Set(["highlight-updates-overlay","__rn_buoy__highlight-modal"]);const Ze=new Set(["jsmodal-root","image-overlay-standalone","logbox_inspector","logbox"]);const H=new Map;const ge=500;function Je(){H.clear()}function pe(e){if(!e)return false;if(Ye.has(e))return true;if(e.startsWith("__highlight_"))return true;return false}function me(e){if(!e)return false;if(Ze.has(e))return true;const n=e.charCodeAt(0);if(n===95){if(e.startsWith("__rn_buoy__"))return true}if(n===108&&e.startsWith("logbox")){return true}return false}function be(e){if(!e)return null;const n=e.type;if(n){if(typeof n==="string")return n;if(n.name)return n.name;if(n.displayName)return n.displayName}const r=e.elementType;if(r){if(r.name)return r.name;if(r.displayName)return r.displayName}return null}const Qe=new Set(["View","Text","TextImpl","Image","ScrollView","FlatList","SectionList","TouchableOpacity","TouchableHighlight","TouchableWithoutFeedback","Pressable","TextInput","Switch","ActivityIndicator","Modal","StatusBar","KeyboardAvoidingView","AnimatedComponent","AnimatedComponentWrapper","ScreenContainer","ScreenStack","Screen","ScreenContentWrapper","Svg","G","Path","Rect","Circle","Line","Polygon","Polyline","Ellipse","Text as SVGText","TSpan","TextPath","Use","Symbol","Defs","ClipPath","LinearGradient","RadialGradient","Stop","Mask","Pattern","Image as SVGImage","SafeAreaProvider","SafeAreaView","SafeAreaListener","GestureHandlerRootView","GestureDetector","ReanimatedView","ReanimatedText","ReanimatedImage","ReanimatedScrollView","Fragment","Suspense","Provider","Consumer","Context","ForwardRef"]);function en(e){if(!e)return true;if(Qe.has(e))return true;if(e==="Unknown"||e==="Component")return true;if(e.startsWith("Animated"))return true;return false}function nn(e){if(!e)return null;let n=e._debugOwner||e.return;let r=0;let o=null;while(n&&r<30){const i=be(n);if(i&&typeof n.type!=="string"){if(!o){o=i}if(!en(i)){return i}}n=n.return;r++}return o}function tn(e){const n=e;const r=n?.canonical?.internalInstanceHandle||n?._internalInstanceHandle||n?._internalFiberInstanceHandleDEV||W(n);const o=R(e)||R(n?.canonical?.publicInstance);const i=We();const a=!i&&v.getSettings().excludeDevTools;if(a&&Oe(e)&&e.closest("[data-buoy-root]"))return true;if(o!=null&&a){const p=H.get(o);if(p!==void 0){return p}}let t=false;const f=r?.pendingProps?.nativeID||r?.memoizedProps?.nativeID||n?.canonical?.currentProps?.nativeID||null;if(pe(f)){t=true}else if(a&&me(f)){t=true}if(!t&&r){let p=r;let h=0;while(p&&h<30){const s=be(p);if(s){if(Me.has(s)){t=true;break}for(const g of Ge){if(s.startsWith(g)){t=true;break}}if(t)break;if(i&&Ke(s)){t=true;break}if(a){if(Be.has(s)||$e.has(s)){t=true;break}for(const g of je){if(s.startsWith(g)){t=true;break}}if(t)break}}const d=p.pendingProps?.nativeID||p.memoizedProps?.nativeID;if(pe(d)){t=true;break}if(a&&me(d)){t=true;break}p=p.return;h++}}if(t&&o!=null&&a){if(H.size>=ge){const p=Array.from(H.keys());for(let h=0;h<ge/2;h++){H.delete(p[h])}}H.set(o,t)}return t}function rn(e){const n=Math.min(e-1,X.length-1);return X[Math.max(0,n)]}function an(e){if(e.size===0){return}if(!w&&!L){return}const n=v.getState();if(n.isPaused){return}if(se.isEnabled()){Ae()}const r=v.getBatchSize();const o=se.startBatch(e.size,r);const i=[];let a=0;let t=0;const f=v.hasActiveFilters();for(const s of e){if(s&&typeof s==="object"){try{if(tn(s)){a++;continue}const d=M(s);const g=R(s)||R(d);if(g==null){continue}const T=Y(s);if(f&&!v.passesFilters(T)){t++;continue}const P=v.getSettings().showRenderCount;let m;let c;if(P){const l=q.get(g)||0;m=l+1;q.set(g,m);c=rn(m)}else{m=0;c=X[0]}i.push({node:s,color:c,count:m})}catch{}}}o.markFilteringComplete(a+t,i.length);if(i.length===0){o.finish();return}if(fe){console.log(`[HighlightUpdates] ${i.length} component(s) re-rendered`)}const p=v.getRenderEventCallbackCount()>0;if(!O&&!p){if(fe){console.log(`[HighlightUpdates] No highlightCallback and no event callbacks - skipping render`)}ue=false;return}o.markMeasurementStart();const h=i.slice(0,r*4).map(({node:s,color:d,count:g})=>new Promise(T=>{let P=false;const m=b=>{if(P)return;P=true;clearTimeout(c);T(b)};const c=setTimeout(()=>m({rect:null,stateNode:s,color:d,count:g}),500);const l=M(s);const E=R(s)||R(l);if(E==null){m({rect:null,stateNode:s,color:d,count:g});return}const I=(b,D,_,S,ie,re)=>{if(ie==null||re==null||_==null||S==null){m({rect:null,stateNode:s,color:d,count:g});return}m({rect:{id:E,x:ie,y:re,width:_,height:S,color:d,count:g},stateNode:s,color:d,count:g})};if(!l){const b=s.node;const D=globalThis.nativeFabricUIManager;if(b&&D?.measure){try{D.measure(b,I)}catch(_){m({rect:null,stateNode:s,color:d,count:g})}return}m({rect:null,stateNode:s,color:d,count:g});return}try{l.measure(I)}catch(b){m({rect:null,stateNode:s,color:d,count:g})}}));Promise.all(h).then(s=>{const d=s.filter(T=>T.rect!==null);const g=d.map(T=>T.rect);o.markMeasurementComplete(d.length,s.length-d.length);if(g.length>0&&O&&w&&!V){O(g)}setTimeout(()=>{try{for(const c of d){if(c.rect)on(c.rect.id,c.stateNode)}}catch(c){u("registerTrackedNode batch failed",c)}const T=v.getSettings();const P=T.trackRenderCauses&&T.showRenderCount;let m=null;if(P){m=new Set;for(const{rect:c}of d){if(c){m.add(c.id)}}}if(w){v.startBatch();for(const{rect:c,stateNode:l,color:E,count:I}of d){if(c){const b=Y(l);let D;if(P&&m){const _=l;const S=J(_);D=le(c.id,S,m,T.debugLogLevel)}v.trackRender({nativeTag:c.id,viewType:b.viewType,testID:b.testID,nativeID:b.nativeID,accessibilityLabel:b.accessibilityLabel,componentName:b.componentName,measurements:{x:c.x,y:c.y,width:c.width,height:c.height},color:E,count:I,renderCause:D})}}v.endBatch()}else{for(const{rect:c,stateNode:l,color:E,count:I}of d){if(c){const b=Y(l);let D;if(P&&m){const _=l;const S=J(_);D=le(c.id,S,m,T.debugLogLevel)}v.emitRenderEvent({nativeTag:c.id,viewType:b.viewType,testID:b.testID,nativeID:b.nativeID,accessibilityLabel:b.accessibilityLabel,componentName:b.componentName,measurements:{x:c.x,y:c.y,width:c.width,height:c.height},color:E,count:I,renderCause:D})}}}o.markTrackingComplete();o.markCallbackComplete();o.finish()},0)}).catch(s=>{console.error("[HighlightUpdates] Error in measurement pipeline:",s);o.finish()})}const he=globalThis.WeakRef;const G=new Map;function on(e,n){if(e==null||n==null||typeof n!=="object"){return}try{G.set(e,he?new he(n):{deref:()=>n})}catch{G.set(e,{deref:()=>n})}}function sn(e){const n=G.get(e);const r=n?.deref();if(!r)G.delete(e);return r??null}function ln(e){return new Promise(n=>{try{e.measure((r,o,i,a,t,f)=>{if(t==null||f==null||i==null||a==null){n(null)}else{n({x:t,y:f,width:i,height:a})}})}catch{n(null)}})}function J(e){const n=e;return n?.canonical?.internalInstanceHandle||n?._internalInstanceHandle||n?._internalFiberInstanceHandleDEV||W(n)||null}function cn(e){let n=J(e);let r=0;while(n&&r++<200){const o=n.stateNode;if(o&&typeof o.scrollTo==="function"){const i=typeof o.getNativeScrollRef==="function"&&o.getNativeScrollRef()||null;const a=typeof o.getInnerViewNode==="function"&&o.getInnerViewNode()||typeof o.getScrollableNode==="function"&&o.getScrollableNode()||o;return{instance:o,nativeRef:i,innerNode:a}}n=n.return}return null}async function un(e,n,r){try{const o=cn(e);if(!o)return false;const i=n;let a=null;const t=f=>new Promise(p=>{let h=false;const s=g=>{if(h)return;h=true;p(g)};const d=setTimeout(()=>s(null),600);try{f(g=>{clearTimeout(d);s(g)})}catch{clearTimeout(d);s(null)}});if(o.nativeRef&&typeof i.measureLayout==="function"){a=await t(f=>i.measureLayout(o.nativeRef,(p,h)=>f(h),()=>f(null)))}if(a==null){const f=ae(n);const p=typeof o.innerNode==="number"?o.innerNode:ae(o.innerNode);if(f!=null&&p!=null){a=await t(h=>Ve.measureLayout(f,p,()=>h(null),(s,d)=>h(d)))}}if(a==null)return false;o.instance.scrollTo({y:Math.max(0,a-r),animated:false});await new Promise(f=>setTimeout(f,80));return true}catch{return false}}function fn(e,n){const r=[e.testID,e.nativeID,e.accessibilityLabel,e.componentName,e.viewType,String(e.nativeTag)];let o=0;for(const i of r){if(!i)continue;const a=i.toLowerCase();if(a===n)return 3;if(a.startsWith(n))o=Math.max(o,2);else if(a.includes(n))o=Math.max(o,1)}return o}async function dn(e){const n=e.scrollIntoView!==false;const r=typeof e.margin==="number"?e.margin:12;const o=v.getRenders();const i=async()=>{const l=await xe();const E=(e.query??"").trim().toLowerCase();let I;for(const _ of l.elements){if(e.nativeTag!=null&&_.nativeTag===e.nativeTag){I={el:_,score:1e3};break}const S=Ue({nativeTag:_.nativeTag,testID:_.testID,label:_.label,text:_.text,name:_.name,tap:_.tap},{query:E||void 0,nativeTag:e.nativeTag});if(S<=0)continue;if(!I||S>I.score)I={el:_,score:S}}if(!I?.el.frame){return{matched:false,reason:"no-match",candidates:[]}}const b=l.screen;const D=I.el.frame;return{matched:true,live:true,rect:{x:D.x*b.width,y:D.y*b.height,width:D.width*b.width,height:D.height*b.height},scale:oe.get(),screen:{width:b.width,height:b.height},nativeTag:I.el.nativeTag??void 0,componentName:I.el.name,testID:I.el.testID}};if(o.length===0)return i();const a=(e.query??"").trim().toLowerCase();const t=a?o.map(l=>({r:l,score:fn(l,a)})).filter(l=>l.score>0).sort((l,E)=>E.score-l.score||E.r.lastRenderTime-l.r.lastRenderTime):[];const f=t.slice(0,8).map(({r:l})=>({nativeTag:l.nativeTag,componentName:l.componentName,testID:l.testID,nativeID:l.nativeID,viewType:l.viewType,renderCount:l.renderCount}));const p=e.nativeTag??(t.length>0?t[0].r.nativeTag:void 0);if(p==null){const l=await i();return l.matched?l:{matched:false,reason:"no-match",candidates:f}}const h=o.find(l=>l.nativeTag===p);let s=null;let d=false;let g=false;const T=sn(p);if(T){const l=M(T);if(l){if(n){g=await un(T,l,r)}s=await ln(l);d=!!s}}if(!s&&h?.measurements){s={...h.measurements}}if(!s){return{matched:false,reason:"no-measurement",nativeTag:p,candidates:f}}const P=oe.get();const m=ze.get("window");const c=s.x>=-1&&s.y>=-1&&s.x+s.width<=m.width+1&&s.y+s.height<=m.height+1;return{matched:true,live:d,scrolled:g,inView:c,rect:s,scale:P,screen:{width:m.width,height:m.height},nativeTag:p,componentName:h?.componentName,testID:h?.testID,candidates:f}}function ye(e){if(!y?.rendererInterfaces){u("No rendererInterfaces available");return}let n=0;y.rendererInterfaces.forEach((r,o)=>{if(typeof r.setTraceUpdatesEnabled==="function"){try{r.setTraceUpdatesEnabled(e);n++;u(`Renderer ${o}: setTraceUpdatesEnabled(${e})`)}catch(i){u(`Renderer ${o}: error setting trace updates`,i)}}else{u(`Renderer ${o}: no setTraceUpdatesEnabled method`)}});u(`Set trace updates ${e?"enabled":"disabled"} on ${n} renderer(s)`);if(y.reactDevtoolsAgent?.setTraceUpdatesEnabled){try{y.reactDevtoolsAgent.setTraceUpdatesEnabled(e);u("Also set trace updates on agent")}catch(r){u("Error setting trace updates on agent",r)}}}function _e(){if(!y)return;if(z)return;u("Subscribing to traceUpdates event");if(typeof y.sub==="function"){z=y.sub("traceUpdates",an);u("Subscribed using hook.sub()")}else{u("hook.sub not available, traceUpdates may not work")}ye(true)}function Q(){ye(false);if(z){z();z=null;u("Unsubscribed from traceUpdates event")}}function Te(e){O=e;u(`Highlight callback ${e?"set":"cleared"}`)}function gn(e){A=e;u(`Badge press callback ${e?"set":"cleared"}`)}function pn(){return A}function mn(e){if(A){A(e)}}let ee=null;let B=null;function bn(e){ee=e;if(e&&B!==null){e(B)}}function hn(e){if(C){C("setSpotlight",{nativeTag:e});return}B=e;if(ee){ee(e)}}let C=null;function yn(e){C=e}function _n(e){if(w!==e.enabled){w=e.enabled;ne()}if(k!==e.frozen){k=e.frozen;j()}}function Tn(){return B}function ne(){K.forEach(e=>{try{e(w)}catch(n){console.error("[HighlightUpdates] Error in state listener:",n)}})}function Ie(e){K.add(e);e(w);return()=>{K.delete(e)}}function $(){if(typeof __DEV__!=="undefined"&&!__DEV__){u("Only available in development builds");return false}if(C){return true}if(N){return true}y=window?.__REACT_DEVTOOLS_GLOBAL_HOOK__||null;if(!y){u("React DevTools hook not found");return false}u("Hook found");u(`Hook has sub: ${typeof y.sub==="function"}`);u(`Hook has on: ${typeof y.on==="function"}`);u(`Hook has emit: ${typeof y.emit==="function"}`);Le();if(y.rendererInterfaces&&y.rendererInterfaces.size>0){N=true;u(`Initialized with ${y.rendererInterfaces.size} renderer(s)`);ve();return true}const e=setInterval(()=>{if(y?.rendererInterfaces&&y.rendererInterfaces.size>0){clearInterval(e);N=true;u(`Initialized with ${y.rendererInterfaces.size} renderer(s) (delayed)`);ve()}},100);setTimeout(()=>clearInterval(e),1e4);return false}function ve(){if(typeof window!=="undefined"){window.__HIGHLIGHT_UPDATES_CONTROLLER__={enable:x,disable:U,toggle:we,isEnabled:De,setEnabled:Ce,subscribe:Ie,initialize:$,destroy:Pe,isInitialized:()=>N,setHighlightCallback:Te}}}function x(){if(typeof __DEV__!=="undefined"&&!__DEV__)return;if(!N){$()}if(V){V=false}if(w){return}u("Enabling highlights");if(!L){_e()}v.start();w=true;ne();ce("render")}function U(){if(typeof __DEV__!=="undefined"&&!__DEV__)return;if(!w){return}u("Disabling highlights");Xe=false;ue=false;if(Z){clearTimeout(Z);Z=null}de.clear();H.clear();Fe();if(k){k=false;j()}if(!L){Q()}v.stop();w=false;ne();ce("render")}function In(){if(typeof __DEV__!=="undefined"&&!__DEV__)return;if(L){return}if(!N){$()}u("Enabling background tracking");if(!w){_e()}L=true}function vn(){if(typeof __DEV__!=="undefined"&&!__DEV__)return;if(!L){return}u("Disabling background tracking");L=false;if(!w){Q()}}function wn(){return L}function we(){if(typeof __DEV__!=="undefined"&&!__DEV__)return;if(C){C("toggle");return}if(w){U()}else{x()}}function Dn(){if(C){C("clearRenderCounts");return}q.clear();v.clear();u("Cleared render counts")}function De(){return w}function Ce(e){if(C){C("setEnabled",{enabled:e});return}if(e)x();else U()}function te(e){if(V===e)return;V=e;if(e&&O){O([])}}function Cn(){return V}function kn(e){if(C){C("setSilentTracking",{enabled:e});return}if(e){x();te(true)}else{te(false);U()}}function En(){return N}function j(){F.forEach(e=>{try{e(k)}catch(n){console.error("[HighlightUpdates] Error in freeze listener:",n)}})}function Pn(e){F.add(e);e(k);return()=>{F.delete(e)}}function ke(){if(typeof __DEV__!=="undefined"&&!__DEV__)return;if(k)return;k=true;u("Freeze mode enabled");j()}function Ee(){if(typeof __DEV__!=="undefined"&&!__DEV__)return;if(!k)return;k=false;u("Freeze mode disabled");if(O){O([])}j()}function Sn(){if(C){C("toggleFreeze");return}if(k){Ee()}else{ke()}}function Nn(){return k}function Pe(){if(!N)return;Q();Re();He(null);k=false;F.clear();w=false;y=null;O=null;N=false;if(typeof window!=="undefined"){delete window.__HIGHLIGHT_UPDATES_CONTROLLER__}u("Destroyed")}const On={subscribe:Ie,enable:x,disable:U,toggle:we,isEnabled:De,setEnabled:Ce,initialize:$,destroy:Pe,isInitialized:En,setHighlightCallback:Te,clearRenderCounts:Dn,freeze:ke,unfreeze:Ee,toggleFreeze:Sn,getFrozen:Nn,subscribeToFreeze:Pn,setBadgePressCallback:gn,getBadgePressCallback:pn,handleBadgePress:mn,setSpotlightCallback:bn,setSpotlight:hn,getSpotlight:Tn,clearDevToolsCache:Je,enableBackgroundTracking:In,disableBackgroundTracking:vn,isBackgroundTrackingEnabled:wn,setRemoteHandler:yn,replaceRemoteState:_n,locateComponent:dn,setHighlightsSuppressed:te,getHighlightsSuppressed:Cn,setSilentTracking:kn};export default On;