@buoy-gg/highlight-updates 7.0.35 → 7.0.38

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