@buoy-gg/highlight-updates 2.1.4-beta.2 → 2.1.5

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 (64) hide show
  1. package/lib/commonjs/highlight-updates/HighlightUpdatesOverlay.js +1 -285
  2. package/lib/commonjs/highlight-updates/components/HighlightFilterView.js +1 -1371
  3. package/lib/commonjs/highlight-updates/components/HighlightUpdatesModal.js +1 -592
  4. package/lib/commonjs/highlight-updates/components/IdentifierBadge.js +1 -267
  5. package/lib/commonjs/highlight-updates/components/IsolatedRenderList.js +1 -178
  6. package/lib/commonjs/highlight-updates/components/ModalHeaderContent.js +1 -303
  7. package/lib/commonjs/highlight-updates/components/RenderCauseBadge.js +1 -500
  8. package/lib/commonjs/highlight-updates/components/RenderDetailView.js +1 -830
  9. package/lib/commonjs/highlight-updates/components/RenderHistoryViewer.js +1 -894
  10. package/lib/commonjs/highlight-updates/components/RenderListItem.js +1 -226
  11. package/lib/commonjs/highlight-updates/components/StatsDisplay.js +1 -70
  12. package/lib/commonjs/highlight-updates/components/index.js +1 -97
  13. package/lib/commonjs/highlight-updates/utils/HighlightUpdatesController.js +1 -1427
  14. package/lib/commonjs/highlight-updates/utils/PerformanceLogger.js +1 -359
  15. package/lib/commonjs/highlight-updates/utils/ProfilerInterceptor.js +1 -371
  16. package/lib/commonjs/highlight-updates/utils/RenderCauseDetector.js +1 -1828
  17. package/lib/commonjs/highlight-updates/utils/RenderTracker.js +1 -903
  18. package/lib/commonjs/highlight-updates/utils/ViewTypeMapper.js +1 -264
  19. package/lib/commonjs/highlight-updates/utils/renderExportFormatter.js +1 -58
  20. package/lib/commonjs/index.js +1 -311
  21. package/lib/commonjs/preset.js +1 -278
  22. package/lib/module/highlight-updates/HighlightUpdatesOverlay.js +1 -278
  23. package/lib/module/highlight-updates/components/HighlightFilterView.js +1 -1365
  24. package/lib/module/highlight-updates/components/HighlightUpdatesModal.js +1 -586
  25. package/lib/module/highlight-updates/components/IdentifierBadge.js +1 -259
  26. package/lib/module/highlight-updates/components/IsolatedRenderList.js +1 -174
  27. package/lib/module/highlight-updates/components/ModalHeaderContent.js +1 -298
  28. package/lib/module/highlight-updates/components/RenderCauseBadge.js +1 -491
  29. package/lib/module/highlight-updates/components/RenderDetailView.js +1 -826
  30. package/lib/module/highlight-updates/components/RenderHistoryViewer.js +1 -888
  31. package/lib/module/highlight-updates/components/RenderListItem.js +1 -221
  32. package/lib/module/highlight-updates/components/StatsDisplay.js +1 -67
  33. package/lib/module/highlight-updates/components/index.js +1 -16
  34. package/lib/module/highlight-updates/utils/HighlightUpdatesController.js +1 -1423
  35. package/lib/module/highlight-updates/utils/PerformanceLogger.js +1 -353
  36. package/lib/module/highlight-updates/utils/ProfilerInterceptor.js +1 -358
  37. package/lib/module/highlight-updates/utils/RenderCauseDetector.js +1 -1818
  38. package/lib/module/highlight-updates/utils/RenderTracker.js +1 -900
  39. package/lib/module/highlight-updates/utils/ViewTypeMapper.js +1 -255
  40. package/lib/module/highlight-updates/utils/renderExportFormatter.js +1 -54
  41. package/lib/module/index.js +1 -71
  42. package/lib/module/preset.js +1 -272
  43. package/package.json +7 -7
  44. package/lib/typescript/highlight-updates/HighlightUpdatesOverlay.d.ts.map +0 -1
  45. package/lib/typescript/highlight-updates/components/HighlightFilterView.d.ts.map +0 -1
  46. package/lib/typescript/highlight-updates/components/HighlightUpdatesModal.d.ts.map +0 -1
  47. package/lib/typescript/highlight-updates/components/IdentifierBadge.d.ts.map +0 -1
  48. package/lib/typescript/highlight-updates/components/IsolatedRenderList.d.ts.map +0 -1
  49. package/lib/typescript/highlight-updates/components/ModalHeaderContent.d.ts.map +0 -1
  50. package/lib/typescript/highlight-updates/components/RenderCauseBadge.d.ts.map +0 -1
  51. package/lib/typescript/highlight-updates/components/RenderDetailView.d.ts.map +0 -1
  52. package/lib/typescript/highlight-updates/components/RenderHistoryViewer.d.ts.map +0 -1
  53. package/lib/typescript/highlight-updates/components/RenderListItem.d.ts.map +0 -1
  54. package/lib/typescript/highlight-updates/components/StatsDisplay.d.ts.map +0 -1
  55. package/lib/typescript/highlight-updates/components/index.d.ts.map +0 -1
  56. package/lib/typescript/highlight-updates/utils/HighlightUpdatesController.d.ts.map +0 -1
  57. package/lib/typescript/highlight-updates/utils/PerformanceLogger.d.ts.map +0 -1
  58. package/lib/typescript/highlight-updates/utils/ProfilerInterceptor.d.ts.map +0 -1
  59. package/lib/typescript/highlight-updates/utils/RenderCauseDetector.d.ts.map +0 -1
  60. package/lib/typescript/highlight-updates/utils/RenderTracker.d.ts.map +0 -1
  61. package/lib/typescript/highlight-updates/utils/ViewTypeMapper.d.ts.map +0 -1
  62. package/lib/typescript/highlight-updates/utils/renderExportFormatter.d.ts.map +0 -1
  63. package/lib/typescript/index.d.ts.map +0 -1
  64. package/lib/typescript/preset.d.ts.map +0 -1
@@ -1,1427 +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 _RenderTracker = require("./RenderTracker");
36
- var _PerformanceLogger = require("./PerformanceLogger");
37
- var _RenderCauseDetector = require("./RenderCauseDetector");
38
- var _sharedUi = require("@buoy-gg/shared-ui");
39
- // State
40
- let globalEnabled = false; // User-controlled toggle for visual highlights
41
- let backgroundTrackingEnabled = false; // Auto-enabled when event callbacks exist (Events tool)
42
- let initialized = false;
43
- let hook = null;
44
- let highlightCallback = null;
45
- let badgePressCallback = null;
46
- let traceUpdatesUnsubscribe = null;
47
- let isProcessing = false;
48
-
49
- // Freeze frame state
50
- let isFrozen = false;
51
- const freezeListeners = new Set();
52
- const stateListeners = new Set();
53
-
54
- // Track render counts per node (for color assignment like DevTools)
55
- // Map from nativeTag to render count - nativeTag is stable across re-renders
56
- const nodeRenderCounts = new Map();
57
-
58
- // Color palette for highlights (same as DevTools)
59
- // From: react-devtools-core/dist/backend.js line 6361
60
- const COLORS = ["#37afa9", "#63b19e", "#80b393", "#97b488", "#abb67d", "#beb771", "#cfb965", "#dfba57", "#efbb49", "#febc38"];
61
-
62
- // Set to true for verbose debugging of our implementation
63
- // Disabled for now to focus on profiler logs only
64
- const DEBUG = false;
65
- function debugLog(message, data) {
66
- if (!DEBUG) return;
67
- if (data !== undefined) {
68
- console.log(`[HighlightUpdates] ${message}`, data);
69
- } else {
70
- console.log(`[HighlightUpdates] ${message}`);
71
- }
72
- }
73
-
74
- /**
75
- * Get the public instance from a stateNode (the node passed in traceUpdates)
76
- */
77
- function getPublicInstance(stateNode) {
78
- if (!stateNode) return null;
79
- const node = stateNode;
80
-
81
- // Fabric: stateNode.canonical.publicInstance
82
- if (node.canonical?.publicInstance) {
83
- return node.canonical.publicInstance;
84
- }
85
-
86
- // Legacy Fabric: stateNode.canonical with measure
87
- if (node.canonical && typeof node.canonical.measure === "function") {
88
- return node.canonical;
89
- }
90
-
91
- // Legacy renderer: stateNode has measure directly
92
- if (typeof node.measure === "function") {
93
- return node;
94
- }
95
- return null;
96
- }
97
-
98
- /**
99
- * Get native tag from public instance or stateNode
100
- */
101
- function getNativeTag(instance) {
102
- const inst = instance;
103
-
104
- // Try direct properties
105
- if (inst.__nativeTag != null) return inst.__nativeTag;
106
- if (inst._nativeTag != null) return inst._nativeTag;
107
- if (inst.nativeTag != null) return inst.nativeTag;
108
-
109
- // Try canonical
110
- if (inst.canonical) {
111
- if (inst.canonical.__nativeTag != null) return inst.canonical.__nativeTag;
112
- if (inst.canonical._nativeTag != null) return inst.canonical._nativeTag;
113
- }
114
- return null;
115
- }
116
-
117
- /**
118
- * Extract component info from a stateNode for RenderTracker
119
- */
120
- function extractComponentInfo(stateNode) {
121
- const node = stateNode;
122
- const info = {
123
- viewType: "Unknown"
124
- };
125
-
126
- // Get viewType from viewConfig
127
- if (node?.canonical?.viewConfig?.uiViewClassName) {
128
- info.viewType = node.canonical.viewConfig.uiViewClassName;
129
- } else if (node?.viewConfig?.uiViewClassName) {
130
- info.viewType = node.viewConfig.uiViewClassName;
131
- }
132
-
133
- // Try to get props from various locations
134
- // Fabric: canonical.internalInstanceHandle, Paper: _internalInstanceHandle, RN CLI DEV: _internalFiberInstanceHandleDEV
135
- const fiber = node?.canonical?.internalInstanceHandle || node?._internalInstanceHandle || node?._internalFiberInstanceHandleDEV;
136
- const currentProps = node?.canonical?.currentProps;
137
- const pendingProps = node?.canonical?.pendingProps;
138
- const fiberPendingProps = fiber?.pendingProps;
139
- const fiberMemoizedProps = fiber?.memoizedProps;
140
-
141
- // Extract testID
142
- info.testID = currentProps?.testID || pendingProps?.testID || fiberPendingProps?.testID || fiberMemoizedProps?.testID || undefined;
143
-
144
- // Extract nativeID
145
- info.nativeID = currentProps?.nativeID || pendingProps?.nativeID || fiberPendingProps?.nativeID || fiberMemoizedProps?.nativeID || undefined;
146
-
147
- // Extract accessibilityLabel
148
- info.accessibilityLabel = currentProps?.accessibilityLabel || pendingProps?.accessibilityLabel || fiberPendingProps?.accessibilityLabel || fiberMemoizedProps?.accessibilityLabel || undefined;
149
-
150
- // Extract componentName - use getOwningComponentName to get the React component
151
- // that rendered this host component
152
- info.componentName = getOwningComponentName(fiber) || undefined;
153
- return info;
154
- }
155
-
156
- /**
157
- * Describe a node for logging (extensive version for debugging)
158
- */
159
- function describeNodeForLog(stateNode) {
160
- const node = stateNode;
161
- const publicInstance = getPublicInstance(stateNode);
162
- const nativeTag = getNativeTag(stateNode) || getNativeTag(publicInstance);
163
- const info = {
164
- nativeTag: nativeTag ?? "unknown",
165
- type: node?.canonical ? "Fabric" : "Legacy",
166
- hasMeasure: typeof publicInstance?.measure === "function"
167
- };
168
-
169
- // Extract as much info as possible from the stateNode
170
- if (node) {
171
- // Direct properties on stateNode
172
- info.stateNodeKeys = Object.keys(node).slice(0, 20);
173
-
174
- // Check the 'node' property (might have useful info)
175
- if (node.node) {
176
- info.nodeKeys = Object.keys(node.node).slice(0, 20);
177
- }
178
-
179
- // Check for viewConfig (contains component type info)
180
- if (node.viewConfig) {
181
- info.viewConfig = {
182
- uiViewClassName: node.viewConfig.uiViewClassName,
183
- validAttributes: node.viewConfig.validAttributes ? Object.keys(node.viewConfig.validAttributes).slice(0, 10) : undefined
184
- };
185
- }
186
-
187
- // Check canonical structure (Fabric)
188
- if (node.canonical) {
189
- const canonical = node.canonical;
190
- info.canonicalKeys = Object.keys(canonical).slice(0, 20);
191
- if (canonical.viewConfig) {
192
- info.canonicalViewConfig = {
193
- uiViewClassName: canonical.viewConfig.uiViewClassName
194
- };
195
- }
196
- if (canonical.nativeTag != null) {
197
- info.canonicalNativeTag = canonical.nativeTag;
198
- }
199
-
200
- // Check internalInstanceHandle (THE FIBER!)
201
- if (canonical.internalInstanceHandle) {
202
- const fiber = canonical.internalInstanceHandle;
203
- info.fiberKeys = Object.keys(fiber).slice(0, 30);
204
-
205
- // Component type info
206
- if (fiber.type) {
207
- info.fiberType = typeof fiber.type === "function" ? fiber.type.name || fiber.type.displayName || "function" : fiber.type;
208
- }
209
- if (fiber.elementType) {
210
- info.fiberElementType = typeof fiber.elementType === "function" ? fiber.elementType.name || fiber.elementType.displayName || "function" : fiber.elementType;
211
- }
212
-
213
- // Debug info on fiber
214
- if (fiber._debugOwner) {
215
- const owner = fiber._debugOwner;
216
- info.fiberDebugOwner = owner.type?.name || owner.type?.displayName || owner.elementType?.name || "unknown";
217
- }
218
- if (fiber._debugSource) {
219
- info.fiberDebugSource = fiber._debugSource;
220
- }
221
-
222
- // Fiber tag (tells us what kind of fiber it is)
223
- if (fiber.tag != null) {
224
- info.fiberTag = fiber.tag;
225
- }
226
-
227
- // pendingProps on fiber might have testID/nativeID
228
- if (fiber.pendingProps) {
229
- if (fiber.pendingProps.nativeID) info.fiberPendingNativeID = fiber.pendingProps.nativeID;
230
- if (fiber.pendingProps.testID) info.fiberPendingTestID = fiber.pendingProps.testID;
231
- }
232
- if (fiber.memoizedProps) {
233
- if (fiber.memoizedProps.nativeID) info.fiberMemoizedNativeID = fiber.memoizedProps.nativeID;
234
- if (fiber.memoizedProps.testID) info.fiberMemoizedTestID = fiber.memoizedProps.testID;
235
- }
236
- }
237
-
238
- // Check publicInstance
239
- if (canonical.publicInstance) {
240
- const pub = canonical.publicInstance;
241
- info.publicInstanceKeys = Object.keys(pub).slice(0, 20);
242
-
243
- // Look for nativeID
244
- if (pub.nativeID != null) info.nativeID = pub.nativeID;
245
- if (pub._nativeID != null) info._nativeID = pub._nativeID;
246
-
247
- // Look for props
248
- if (pub.props) {
249
- info.publicInstanceProps = Object.keys(pub.props).slice(0, 15);
250
- if (pub.props.nativeID) info.propsNativeID = pub.props.nativeID;
251
- if (pub.props.testID) info.propsTestID = pub.props.testID;
252
- if (pub.props.accessibilityLabel) info.accessibilityLabel = pub.props.accessibilityLabel;
253
- }
254
- }
255
-
256
- // Check for currentProps - log actual VALUES
257
- if (canonical.currentProps) {
258
- info.currentPropsKeys = Object.keys(canonical.currentProps).slice(0, 15);
259
- // Log actual values of identifying props
260
- if (canonical.currentProps.nativeID != null) info.currentPropsNativeID = canonical.currentProps.nativeID;
261
- if (canonical.currentProps.testID != null) info.currentPropsTestID = canonical.currentProps.testID;
262
- if (canonical.currentProps.accessibilityLabel != null) info.currentPropsAccessLabel = canonical.currentProps.accessibilityLabel;
263
- }
264
-
265
- // Check for pendingProps
266
- if (canonical.pendingProps) {
267
- info.pendingPropsKeys = Object.keys(canonical.pendingProps).slice(0, 15);
268
- if (canonical.pendingProps.nativeID != null) info.pendingPropsNativeID = canonical.pendingProps.nativeID;
269
- if (canonical.pendingProps.testID != null) info.pendingPropsTestID = canonical.pendingProps.testID;
270
- }
271
- }
272
-
273
- // Check for fiber reference directly on node
274
- if (node._debugOwner) {
275
- const owner = node._debugOwner;
276
- info.debugOwnerType = owner.type?.name || owner.type?.displayName || typeof owner.type;
277
- }
278
- if (node._debugSource) {
279
- info.debugSource = node._debugSource;
280
- }
281
- }
282
- return info;
283
- }
284
-
285
- // Set to true to enable debug logging
286
- const DEBUG_LOGGING = false;
287
-
288
- // Lock to prevent infinite loops when rendering our overlay
289
- let renderingLock = false;
290
- let renderingLockTimeout = null;
291
-
292
- // How long to ignore new events after starting a render (ms)
293
- // Should match HIGHLIGHT_DURATION in the overlay to prevent false triggers
294
- const RENDER_LOCK_DURATION = 350;
295
-
296
- // Track nativeTags of components we're currently highlighting
297
- // This helps us identify (and skip) our own overlay Views if they re-render
298
- const renderedOverlayTags = new Set();
299
-
300
- /**
301
- * Check if a nativeTag belongs to our overlay (was rendered by us previously)
302
- */
303
- function isOurOverlayTag(nativeTag) {
304
- if (nativeTag == null) return false;
305
- return renderedOverlayTags.has(nativeTag);
306
- }
307
-
308
- // ============================================================================
309
- // OPTIMIZED DEV TOOLS DETECTION
310
- // ============================================================================
311
- // Performance optimizations applied:
312
- // 1. Result caching by nativeTag (same tag = same result)
313
- // 2. Set-based O(1) lookups instead of multiple string comparisons
314
- // 3. Component name check FIRST (appears early in tree, ~depth 5-8)
315
- // 4. Early exit on first match
316
- // 5. Cached property access to avoid repeated traversal
317
- // ============================================================================
318
-
319
- // Components that MUST always be excluded to prevent infinite loops.
320
- // Includes the Highlight Updates overlay AND the Events tool (which subscribes
321
- // to render callbacks via RenderTracker.onRenderEvent - tracking its renders
322
- // would create an infinite callback loop).
323
- const HIGHLIGHT_OVERLAY_COMPONENTS = new Set([
324
- // Highlight Updates overlay components
325
- "HighlightUpdatesOverlay", "HighlightUpdatesModal", "HighlightFilterView", "RenderDetailView", "RenderListItem", "RenderListItemInner", "RenderHistoryViewer", "RenderHistoryFooter", "RenderCauseBadge", "TwoLevelCauseBadge", "EnhancedCauseDisplay", "IsolatedRenderList", "IsolatedRenderListInner", "StatsDisplay", "StatsDisplayInner", "CurrentStateView", "EventStepperFooter",
326
- // Events tool components - subscribes to onRenderEvent, tracking these causes infinite loops
327
- "EventsModal", "UnifiedEventList", "UnifiedEventItem", "UnifiedEventDetail", "UnifiedEventFilters", "UnifiedEventViewer", "ReactQueryEventDetail", "EventsCopySettingsView"]);
328
-
329
- // Native IDs that MUST always be excluded (highlight overlay)
330
- const HIGHLIGHT_OVERLAY_NATIVE_IDS = new Set(["highlight-updates-overlay", "__rn_buoy__highlight-modal"]);
331
-
332
- // Prefixes for always-excluded components (highlight overlay + events tool)
333
- const HIGHLIGHT_OVERLAY_PREFIXES = ["HighlightUpdates", "RenderList", "RenderDetail", "RenderHistory", "RenderCause", "EventStepper",
334
- // Events tool - subscribes to onRenderEvent, must always be excluded
335
- "UnifiedEvent", "EventsModal", "EventsCopy"];
336
-
337
- // Other dev tools components - can be toggled via excludeDevTools setting
338
- const OTHER_DEV_TOOLS_COMPONENTS = new Set([
339
- // React Buoy devtools components
340
- "JsModalComponent", "JsModal", "TypePicker", "PatternInput", "PatternChip", "DetectedItemsSection", "DetectedCategoryBadge", "IdentifierBadge", "CategoryBadge", "AppRenderer", "AppOverlay", "FloatingTools", "DialDevTools", "DevToolsVisibilityProvider", "AppHostProvider", "MinimizedToolsProvider",
341
- // Shared UI components used in modals
342
- "ModalHeader", "TabSelector", "SectionHeader", "DraggableHeader", "WindowControls",
343
- // Shared UI data viewer components (JSON diff viewers, etc.)
344
- "TreeDiffViewer", "DataViewer", "SplitDiffViewer", "VirtualizedDataExplorer", "DiffSummary", "TypeLegend", "IndentGuides", "IndentGuidesOverlay", "CyberpunkInput", "DiffView", "AnswerCard", "DetailsSection", "DetailRow", "QuickActionsSection", "FilterOptionCard",
345
- // Modal header sub-components
346
- "SearchSection", "SearchSectionInner", "HeaderActions", "HeaderActionsInner", "MainListHeader", "FilterViewHeader", "DetailViewHeader",
347
- // Floating menu components (minimized tools, dial, etc.)
348
- "FloatingMenu", "FloatingDevTools", "MinimizedToolsStack", "MinimizedToolsContext", "GlitchToolButton", "ExpandablePopover", "CollapsedPeek", "ExpandedWrapper", "DialIcon", "DialMenu", "DialIconItem", "OnboardingTooltip", "MenuLauncherIcon", "DevToolsSettingsModal", "SettingsModal", "ToolCard", "ToolIcon", "GripVerticalIcon", "UserStatus", "Divider",
349
- // Shared UI icon components (Chevrons, etc.)
350
- "ChevronDown", "ChevronUp", "ChevronLeft", "ChevronRight", "ChevronDownIcon", "ChevronUpIcon", "ChevronLeftIcon", "ChevronRightIcon",
351
- // React Native LogBox components (shown on reload/errors)
352
- "LogBox", "LogBoxLog", "LogBoxLogNotification", "LogBoxNotificationContainer", "_LogBoxNotificationContainer", "LogBoxInspector", "LogBoxInspectorContainer", "LogBoxInspectorHeader", "LogBoxInspectorBody", "LogBoxInspectorFooter", "LogBoxInspectorMessageHeader", "LogBoxInspectorStackFrame", "LogBoxInspectorSection", "LogBoxButton", "LogBoxMessage"]);
353
-
354
- // Other dev tools prefixes - can be toggled via excludeDevTools setting
355
- const OTHER_DEV_TOOLS_PREFIXES = ["JsModal", "TreeDiff", "DataViewer", "DiffView", "DiffSummary", "Virtualized",
356
- // Floating menu prefixes
357
- "Floating", "Minimized", "Dial", "Expandable", "Chevron", "Glitch", "Settings", "Onboarding", "DevTools"];
358
-
359
- // Other dev tools native IDs - can be toggled
360
- const OTHER_DEV_TOOLS_NATIVE_IDS = new Set(["jsmodal-root",
361
- // LogBox native IDs
362
- "logbox_inspector", "logbox"]);
363
-
364
- // Cache: nativeTag -> isDevTools (avoid re-walking tree for same node)
365
- const devToolsNodeCache = new Map();
366
- const CACHE_MAX_SIZE = 500;
367
-
368
- /**
369
- * Clear the devtools node cache.
370
- * Call this when the excludeDevTools setting changes to re-evaluate all nodes.
371
- */
372
- function clearDevToolsCache() {
373
- devToolsNodeCache.clear();
374
- }
375
-
376
- /**
377
- * Check if a nativeID belongs to highlight overlay (always excluded)
378
- */
379
- function isHighlightOverlayNativeID(nativeID) {
380
- if (!nativeID) return false;
381
- // Direct Set lookup (O(1))
382
- if (HIGHLIGHT_OVERLAY_NATIVE_IDS.has(nativeID)) return true;
383
- // Prefix check for highlight overlay
384
- if (nativeID.startsWith("__highlight_")) return true;
385
- return false;
386
- }
387
-
388
- /**
389
- * Check if a nativeID belongs to other dev tools (optionally excluded)
390
- */
391
- function isOtherDevToolsNativeID(nativeID) {
392
- if (!nativeID) return false;
393
- // Direct Set lookup (O(1))
394
- if (OTHER_DEV_TOOLS_NATIVE_IDS.has(nativeID)) return true;
395
- // Prefix checks for other devtools nativeIDs
396
- const firstChar = nativeID.charCodeAt(0);
397
- if (firstChar === 95) {
398
- // '_' = 95
399
- if (nativeID.startsWith("__rn_buoy__")) return true;
400
- }
401
- // Check for LogBox nativeIDs (start with 'l')
402
- if (firstChar === 108 && nativeID.startsWith("logbox")) {
403
- // 'l' = 108
404
- return true;
405
- }
406
- return false;
407
- }
408
-
409
- /**
410
- * Get component name from fiber (cached property access pattern)
411
- * For host components (RCTView, RCTText), returns the native type.
412
- * Use getOwningComponentName to get the React component that rendered it.
413
- */
414
- function getComponentName(fiber) {
415
- if (!fiber) return null;
416
- // Most common: type.name
417
- const type = fiber.type;
418
- if (type) {
419
- if (typeof type === 'string') return type;
420
- if (type.name) return type.name;
421
- if (type.displayName) return type.displayName;
422
- }
423
- // Fallback: elementType
424
- const elementType = fiber.elementType;
425
- if (elementType) {
426
- if (elementType.name) return elementType.name;
427
- if (elementType.displayName) return elementType.displayName;
428
- }
429
- return null;
430
- }
431
-
432
- // Common React Native internal component names to skip when finding user components
433
- const INTERNAL_COMPONENT_NAMES = new Set([
434
- // React Native core
435
- 'View', 'Text', 'TextImpl', 'Image', 'ScrollView', 'FlatList', 'SectionList', 'TouchableOpacity', 'TouchableHighlight', 'TouchableWithoutFeedback', 'Pressable', 'TextInput', 'Switch', 'ActivityIndicator', 'Modal', 'StatusBar', 'KeyboardAvoidingView',
436
- // Animated components
437
- 'AnimatedComponent', 'AnimatedComponentWrapper',
438
- // React Navigation / Screens
439
- 'ScreenContainer', 'ScreenStack', 'Screen', 'ScreenContentWrapper',
440
- // SVG components
441
- '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',
442
- // SafeArea
443
- 'SafeAreaProvider', 'SafeAreaView', 'SafeAreaListener',
444
- // Gesture Handler
445
- 'GestureHandlerRootView', 'GestureDetector',
446
- // Reanimated
447
- 'ReanimatedView', 'ReanimatedText', 'ReanimatedImage', 'ReanimatedScrollView',
448
- // Common wrapper names
449
- 'Fragment', 'Suspense', 'Provider', 'Consumer', 'Context', 'ForwardRef']);
450
-
451
- /**
452
- * Check if a component name is an internal/wrapper component that should be skipped
453
- */
454
- function isInternalComponent(name) {
455
- if (!name) return true;
456
- if (INTERNAL_COMPONENT_NAMES.has(name)) return true;
457
- // Skip anonymous components and common patterns
458
- if (name === 'Unknown' || name === 'Component') return true;
459
- // Skip Animated.* wrappers
460
- if (name.startsWith('Animated')) return true;
461
- return false;
462
- }
463
-
464
- /**
465
- * Get the owning React component name for a host fiber.
466
- * Walks up the fiber tree to find the first user-defined component,
467
- * skipping React Native internal components.
468
- */
469
- function getOwningComponentName(fiber) {
470
- if (!fiber) return null;
471
-
472
- // Walk up the fiber tree looking for a user-defined component
473
- let current = fiber._debugOwner || fiber.return;
474
- let depth = 0;
475
- let firstNonHostName = null;
476
- while (current && depth < 30) {
477
- const name = getComponentName(current);
478
-
479
- // Skip host components (their type is a string like "RCTView")
480
- if (name && typeof current.type !== 'string') {
481
- // Remember the first non-host component as fallback
482
- if (!firstNonHostName) {
483
- firstNonHostName = name;
484
- }
485
- // Return this component if it's not an internal wrapper
486
- if (!isInternalComponent(name)) {
487
- return name;
488
- }
489
- }
490
- current = current.return;
491
- depth++;
492
- }
493
-
494
- // Fallback to first non-host component found (even if internal)
495
- return firstNonHostName;
496
- }
497
-
498
- /**
499
- * Check if a stateNode belongs to our dev tools.
500
- *
501
- * OPTIMIZED: Uses caching, O(1) Set lookups, and early exit patterns.
502
- * Walks up fiber tree checking component names (fast) before nativeIDs.
503
- *
504
- * When excludeDevTools setting is false, only the Highlight Updates overlay
505
- * is excluded (to prevent infinite loops). Other dev tools will be highlighted.
506
- */
507
- function isOurOverlayNode(stateNode) {
508
- const node = stateNode;
509
- // Fabric: fiber is at canonical.internalInstanceHandle
510
- // Paper/Legacy: fiber is at _internalInstanceHandle directly on stateNode
511
- // RN CLI DEV: fiber is at _internalFiberInstanceHandleDEV
512
- const fiber = node?.canonical?.internalInstanceHandle || node?._internalInstanceHandle || node?._internalFiberInstanceHandleDEV;
513
-
514
- // Get nativeTag for caching
515
- const nativeTag = getNativeTag(stateNode) || getNativeTag(node?.canonical?.publicInstance);
516
-
517
- // Check if we should exclude all dev tools or just highlight overlay
518
- const excludeDevTools = _RenderTracker.RenderTracker.getSettings().excludeDevTools;
519
-
520
- // Check cache first (O(1)) - but only for the current excludeDevTools setting
521
- // When excludeDevTools is false, skip cache to re-evaluate all nodes
522
- if (nativeTag != null && excludeDevTools) {
523
- const cached = devToolsNodeCache.get(nativeTag);
524
- if (cached !== undefined) {
525
- return cached;
526
- }
527
- }
528
- let result = false;
529
-
530
- // Fast path: check direct nativeID
531
- const directNativeID = fiber?.pendingProps?.nativeID || fiber?.memoizedProps?.nativeID || node?.canonical?.currentProps?.nativeID || null;
532
-
533
- // Always check highlight overlay nativeIDs first (must always be excluded)
534
- if (isHighlightOverlayNativeID(directNativeID)) {
535
- result = true;
536
- } else if (excludeDevTools && isOtherDevToolsNativeID(directNativeID)) {
537
- // Only check other dev tools if excludeDevTools is enabled
538
- result = true;
539
- }
540
- if (!result && fiber) {
541
- // Walk up fiber tree - check component names FIRST (they appear early)
542
- let current = fiber;
543
- let depth = 0;
544
-
545
- // Reduced max depth - component names appear by depth 15 typically
546
- while (current && depth < 30) {
547
- // Component name check FIRST (faster, appears earlier in tree)
548
- const name = getComponentName(current);
549
- if (name) {
550
- // Always check highlight overlay components (must always be excluded)
551
- if (HIGHLIGHT_OVERLAY_COMPONENTS.has(name)) {
552
- result = true;
553
- break;
554
- }
555
- // Check highlight overlay prefixes
556
- for (const prefix of HIGHLIGHT_OVERLAY_PREFIXES) {
557
- if (name.startsWith(prefix)) {
558
- result = true;
559
- break;
560
- }
561
- }
562
- if (result) break;
563
-
564
- // Only check other dev tools if excludeDevTools is enabled
565
- if (excludeDevTools) {
566
- if (OTHER_DEV_TOOLS_COMPONENTS.has(name)) {
567
- result = true;
568
- break;
569
- }
570
- // Check other dev tools prefixes
571
- for (const prefix of OTHER_DEV_TOOLS_PREFIXES) {
572
- if (name.startsWith(prefix)) {
573
- result = true;
574
- break;
575
- }
576
- }
577
- if (result) break;
578
- }
579
- }
580
-
581
- // NativeID check (only if component name didn't match)
582
- const nativeID = current.pendingProps?.nativeID || current.memoizedProps?.nativeID;
583
- if (isHighlightOverlayNativeID(nativeID)) {
584
- result = true;
585
- break;
586
- }
587
- if (excludeDevTools && isOtherDevToolsNativeID(nativeID)) {
588
- result = true;
589
- break;
590
- }
591
- current = current.return;
592
- depth++;
593
- }
594
- }
595
-
596
- // Only cache positive results when excludeDevTools is true (default mode)
597
- // Don't cache when excludeDevTools is false to avoid complex cache invalidation
598
- if (result && nativeTag != null && excludeDevTools) {
599
- if (devToolsNodeCache.size >= CACHE_MAX_SIZE) {
600
- // Clear oldest entries (simple strategy - clear half)
601
- const entries = Array.from(devToolsNodeCache.keys());
602
- for (let i = 0; i < CACHE_MAX_SIZE / 2; i++) {
603
- devToolsNodeCache.delete(entries[i]);
604
- }
605
- }
606
- devToolsNodeCache.set(nativeTag, result);
607
- }
608
- return result;
609
- }
610
-
611
- /**
612
- * Get color based on render count (same algorithm as DevTools)
613
- * More renders = warmer color (cyan → yellow)
614
- */
615
- function getColorForRenderCount(count) {
616
- // Clamp to color array bounds
617
- const index = Math.min(count - 1, COLORS.length - 1);
618
- return COLORS[Math.max(0, index)];
619
- }
620
-
621
- /**
622
- * Handle traceUpdates event from DevTools backend
623
- * This is called with a Set of stateNodes that should be highlighted
624
- *
625
- * Strategy to prevent infinite loops:
626
- * 1. Use a rendering lock while rendering highlights
627
- * 2. Use an isProcessing flag to prevent concurrent processing
628
- * 3. If Chrome DevTools agent is available, use native overlay (faster, no React)
629
- * 4. Otherwise, use our React overlay with locks to prevent cascading renders
630
- */
631
- function handleTraceUpdates(nodes) {
632
- if (nodes.size === 0) {
633
- return;
634
- }
635
-
636
- // Skip if neither visual toggle nor background tracking is enabled
637
- if (!globalEnabled && !backgroundTrackingEnabled) {
638
- return;
639
- }
640
-
641
- // Skip processing when paused - don't count renders or show highlights
642
- const trackerState = _RenderTracker.RenderTracker.getState();
643
- if (trackerState.isPaused) {
644
- return;
645
- }
646
-
647
- // Mark event received for end-to-end timing
648
- if (_PerformanceLogger.PerformanceLogger.isEnabled()) {
649
- (0, _PerformanceLogger.markEventReceived)();
650
- }
651
-
652
- // Start performance timing
653
- const batchSize = _RenderTracker.RenderTracker.getBatchSize();
654
- const perfTimer = _PerformanceLogger.PerformanceLogger.startBatch(nodes.size, batchSize);
655
-
656
- // NOTE: Lock-based skipping disabled - relying on nativeID filtering instead
657
- // If nativeID filtering doesn't work, re-enable this:
658
- //
659
- // if (renderingLock || isProcessing) {
660
- // if (DEBUG_LOGGING) {
661
- // console.log(`[HighlightUpdates] SKIPPED - lock:${renderingLock} processing:${isProcessing}`);
662
- // }
663
- // return;
664
- // }
665
- // isProcessing = true;
666
-
667
- // Process nodes: track render counts and assign colors
668
- // Filter out our own overlay nodes to prevent infinite loop
669
- // Also apply user-defined filters to both overlay AND tracking
670
- const nodesToDraw = [];
671
- let skippedOverlayCount = 0;
672
- let skippedByFilterCount = 0;
673
- const hasActiveFilters = _RenderTracker.RenderTracker.hasActiveFilters();
674
- for (const stateNode of nodes) {
675
- if (stateNode && typeof stateNode === "object") {
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
- }
721
- }
722
-
723
- // Mark filtering phase complete (includes both overlay nodes and user-filtered nodes)
724
- perfTimer.markFilteringComplete(skippedOverlayCount + skippedByFilterCount, nodesToDraw.length);
725
-
726
- // Only log if there are real updates (not just overlay re-renders)
727
- if (nodesToDraw.length === 0) {
728
- // All nodes were overlay nodes - silently skip
729
- perfTimer.finish(); // Still log the batch even if empty
730
- return;
731
- }
732
-
733
- // Log actual component updates
734
- if (DEBUG_LOGGING) {
735
- console.log(`[HighlightUpdates] ${nodesToDraw.length} component(s) re-rendered`);
736
- }
737
-
738
- // NOTE: We prefer our React overlay for standalone operation.
739
- // The native overlay only works when Chrome DevTools profiler is actively enabled.
740
- // Uncomment below to use native overlay when available:
741
- //
742
- // const agent = hook?.reactDevtoolsAgent;
743
- // if (agent?.emit) {
744
- // if (DEBUG_LOGGING) {
745
- // console.log(`[HighlightUpdates] Using native overlay (agent available)`);
746
- // }
747
- // agent.emit("drawTraceUpdates", nodesToDraw);
748
- // isProcessing = false;
749
- // return;
750
- // }
751
-
752
- // Check if we should process - either we have a visual callback OR event callbacks
753
- const hasEventCallbacks = _RenderTracker.RenderTracker.getRenderEventCallbackCount() > 0;
754
- if (!highlightCallback && !hasEventCallbacks) {
755
- if (DEBUG_LOGGING) {
756
- console.log(`[HighlightUpdates] No highlightCallback and no event callbacks - skipping render`);
757
- }
758
- isProcessing = false;
759
- return;
760
- }
761
-
762
- // NOTE: Lock disabled - relying on nativeID filtering instead
763
-
764
- // Measure each node and call the highlight callback
765
- // Use batch size from RenderTracker settings (default: 150)
766
- // Note: batchSize already retrieved above for perfTimer
767
- perfTimer.markMeasurementStart();
768
- const measurePromises = nodesToDraw.slice(0, batchSize).map(({
769
- node: stateNode,
770
- color,
771
- count
772
- }) => new Promise(resolve => {
773
- const publicInstance = getPublicInstance(stateNode);
774
- if (!publicInstance) {
775
- resolve({
776
- rect: null,
777
- stateNode,
778
- color,
779
- count
780
- });
781
- return;
782
- }
783
- const nativeTag = getNativeTag(stateNode) || getNativeTag(publicInstance);
784
- if (nativeTag == null) {
785
- resolve({
786
- rect: null,
787
- stateNode,
788
- color,
789
- count
790
- });
791
- return;
792
- }
793
- try {
794
- publicInstance.measure((x, y, width, height, pageX, pageY) => {
795
- if (pageX == null || pageY == null || width == null || height == null) {
796
- resolve({
797
- rect: null,
798
- stateNode,
799
- color,
800
- count
801
- });
802
- return;
803
- }
804
- resolve({
805
- rect: {
806
- id: nativeTag,
807
- x: pageX,
808
- y: pageY,
809
- width,
810
- height,
811
- color,
812
- count
813
- },
814
- stateNode,
815
- color,
816
- count
817
- });
818
- });
819
- } catch (error) {
820
- resolve({
821
- rect: null,
822
- stateNode,
823
- color,
824
- count
825
- });
826
- }
827
- }));
828
- Promise.all(measurePromises).then(results => {
829
- const validResults = results.filter(r => r.rect !== null);
830
- const rects = validResults.map(r => r.rect);
831
-
832
- // Mark measurement phase complete
833
- perfTimer.markMeasurementComplete(validResults.length, results.length - validResults.length);
834
-
835
- // Track renders - behavior differs based on what's enabled:
836
- // - globalEnabled (visual tool): full tracking with storage and list updates
837
- // - backgroundTrackingEnabled only (Events tool): emit events only, no storage
838
- const settings = _RenderTracker.RenderTracker.getSettings();
839
- const trackCauses = settings.trackRenderCauses && settings.showRenderCount;
840
- let batchNativeTags = null;
841
- if (trackCauses) {
842
- batchNativeTags = new Set();
843
- for (const {
844
- rect
845
- } of validResults) {
846
- if (rect) {
847
- batchNativeTags.add(rect.id);
848
- }
849
- }
850
- }
851
- if (globalEnabled) {
852
- // Visual tool is on - full tracking with storage and list notifications
853
- _RenderTracker.RenderTracker.startBatch();
854
- for (const {
855
- rect,
856
- stateNode,
857
- color,
858
- count
859
- } of validResults) {
860
- if (rect) {
861
- const componentInfo = extractComponentInfo(stateNode);
862
- let renderCause;
863
- if (trackCauses && batchNativeTags) {
864
- const node = stateNode;
865
- const fiber = node?.canonical?.internalInstanceHandle;
866
- renderCause = (0, _RenderCauseDetector.detectRenderCause)(rect.id, fiber, batchNativeTags, settings.debugLogLevel);
867
- }
868
- _RenderTracker.RenderTracker.trackRender({
869
- nativeTag: rect.id,
870
- viewType: componentInfo.viewType,
871
- testID: componentInfo.testID,
872
- nativeID: componentInfo.nativeID,
873
- accessibilityLabel: componentInfo.accessibilityLabel,
874
- componentName: componentInfo.componentName,
875
- measurements: {
876
- x: rect.x,
877
- y: rect.y,
878
- width: rect.width,
879
- height: rect.height
880
- },
881
- color,
882
- count,
883
- renderCause
884
- });
885
- }
886
- }
887
- _RenderTracker.RenderTracker.endBatch();
888
- } else {
889
- // Only background tracking (Events tool) - emit events without storage
890
- for (const {
891
- rect,
892
- stateNode,
893
- color,
894
- count
895
- } of validResults) {
896
- if (rect) {
897
- const componentInfo = extractComponentInfo(stateNode);
898
- let renderCause;
899
- if (trackCauses && batchNativeTags) {
900
- const node = stateNode;
901
- const fiber = node?.canonical?.internalInstanceHandle;
902
- renderCause = (0, _RenderCauseDetector.detectRenderCause)(rect.id, fiber, batchNativeTags, settings.debugLogLevel);
903
- }
904
- _RenderTracker.RenderTracker.emitRenderEvent({
905
- nativeTag: rect.id,
906
- viewType: componentInfo.viewType,
907
- testID: componentInfo.testID,
908
- nativeID: componentInfo.nativeID,
909
- accessibilityLabel: componentInfo.accessibilityLabel,
910
- componentName: componentInfo.componentName,
911
- measurements: {
912
- x: rect.x,
913
- y: rect.y,
914
- width: rect.width,
915
- height: rect.height
916
- },
917
- color,
918
- count,
919
- renderCause
920
- });
921
- }
922
- }
923
- }
924
-
925
- // Mark tracking phase complete
926
- perfTimer.markTrackingComplete();
927
-
928
- // Only show visual highlights when the visual tool is enabled (not just background tracking)
929
- if (rects.length > 0 && highlightCallback && globalEnabled) {
930
- highlightCallback(rects);
931
- }
932
-
933
- // Mark callback phase complete and finish timing
934
- perfTimer.markCallbackComplete();
935
- perfTimer.finish();
936
- }).catch(error => {
937
- console.error("[HighlightUpdates] Error in measurement pipeline:", error);
938
- perfTimer.finish(); // Still log timing even on error
939
- });
940
- }
941
-
942
- /**
943
- * Enable or disable trace updates on all renderer interfaces.
944
- * This is the key function that makes standalone tracing work!
945
- *
946
- * The rendererInterfaces map contains the renderer backend for each React root.
947
- * Each renderer has a setTraceUpdatesEnabled function that controls whether
948
- * it emits 'traceUpdates' events when components re-render.
949
- *
950
- * See: react-devtools-core/dist/backend.js line 15487-15489
951
- */
952
- function setTraceUpdatesOnRenderers(enabled) {
953
- if (!hook?.rendererInterfaces) {
954
- debugLog("No rendererInterfaces available");
955
- return;
956
- }
957
- let count = 0;
958
- hook.rendererInterfaces.forEach((rendererInterface, rendererId) => {
959
- if (typeof rendererInterface.setTraceUpdatesEnabled === "function") {
960
- try {
961
- rendererInterface.setTraceUpdatesEnabled(enabled);
962
- count++;
963
- debugLog(`Renderer ${rendererId}: setTraceUpdatesEnabled(${enabled})`);
964
- } catch (error) {
965
- debugLog(`Renderer ${rendererId}: error setting trace updates`, error);
966
- }
967
- } else {
968
- debugLog(`Renderer ${rendererId}: no setTraceUpdatesEnabled method`);
969
- }
970
- });
971
- debugLog(`Set trace updates ${enabled ? "enabled" : "disabled"} on ${count} renderer(s)`);
972
-
973
- // Also try the agent if available (in case DevTools is connected)
974
- if (hook.reactDevtoolsAgent?.setTraceUpdatesEnabled) {
975
- try {
976
- hook.reactDevtoolsAgent.setTraceUpdatesEnabled(enabled);
977
- debugLog("Also set trace updates on agent");
978
- } catch (error) {
979
- debugLog("Error setting trace updates on agent", error);
980
- }
981
- }
982
- }
983
-
984
- /**
985
- * Subscribe to the traceUpdates event from the hook
986
- */
987
- function subscribeToTraceUpdates() {
988
- if (!hook) return;
989
- if (traceUpdatesUnsubscribe) return; // Already subscribed
990
-
991
- debugLog("Subscribing to traceUpdates event");
992
-
993
- // The hook uses EventEmitter pattern with 'sub' method
994
- // See: react-devtools-core/dist/backend.js line 17526
995
- // hook.sub('traceUpdates', agent.onTraceUpdates)
996
- if (typeof hook.sub === "function") {
997
- traceUpdatesUnsubscribe = hook.sub("traceUpdates", handleTraceUpdates);
998
- debugLog("Subscribed using hook.sub()");
999
- } else {
1000
- debugLog("hook.sub not available, traceUpdates may not work");
1001
- }
1002
-
1003
- // CRITICAL: Enable trace updates on all renderers
1004
- // Without this, the renderers won't emit traceUpdates events
1005
- setTraceUpdatesOnRenderers(true);
1006
- }
1007
-
1008
- /**
1009
- * Unsubscribe from the traceUpdates event
1010
- */
1011
- function unsubscribeFromTraceUpdates() {
1012
- // Disable trace updates on renderers first
1013
- setTraceUpdatesOnRenderers(false);
1014
- if (traceUpdatesUnsubscribe) {
1015
- traceUpdatesUnsubscribe();
1016
- traceUpdatesUnsubscribe = null;
1017
- debugLog("Unsubscribed from traceUpdates event");
1018
- }
1019
- }
1020
-
1021
- /**
1022
- * Set the callback for rendering highlights
1023
- */
1024
- function setHighlightCallback(callback) {
1025
- highlightCallback = callback;
1026
- debugLog(`Highlight callback ${callback ? "set" : "cleared"}`);
1027
- }
1028
-
1029
- /**
1030
- * Set the callback for when a badge is pressed.
1031
- * This is used to navigate to the detail view when a user taps a render count badge.
1032
- */
1033
- function setBadgePressCallback(callback) {
1034
- badgePressCallback = callback;
1035
- debugLog(`Badge press callback ${callback ? "set" : "cleared"}`);
1036
- }
1037
-
1038
- /**
1039
- * Get the current badge press callback.
1040
- * Used by the overlay to check if badge presses should be handled.
1041
- */
1042
- function getBadgePressCallback() {
1043
- return badgePressCallback;
1044
- }
1045
-
1046
- /**
1047
- * Handle a badge press event.
1048
- * Calls the registered callback with the nativeTag of the component.
1049
- */
1050
- function handleBadgePress(nativeTag) {
1051
- if (badgePressCallback) {
1052
- badgePressCallback(nativeTag);
1053
- }
1054
- }
1055
-
1056
- // Spotlight highlight state - for showing which component is being viewed in detail
1057
-
1058
- let spotlightCallback = null;
1059
- let currentSpotlightTag = null;
1060
-
1061
- /**
1062
- * Set the callback for spotlight highlighting.
1063
- * Used by the overlay to show a special highlight for the component being viewed.
1064
- */
1065
- function setSpotlightCallback(callback) {
1066
- spotlightCallback = callback;
1067
- // If there's an existing spotlight, notify the new callback
1068
- if (callback && currentSpotlightTag !== null) {
1069
- callback(currentSpotlightTag);
1070
- }
1071
- }
1072
-
1073
- /**
1074
- * Set a spotlight highlight on a specific component.
1075
- * This is used when viewing a component's detail to show which one it is.
1076
- */
1077
- function setSpotlight(nativeTag) {
1078
- currentSpotlightTag = nativeTag;
1079
- if (spotlightCallback) {
1080
- spotlightCallback(nativeTag);
1081
- }
1082
- }
1083
-
1084
- /**
1085
- * Get the current spotlight nativeTag.
1086
- */
1087
- function getSpotlight() {
1088
- return currentSpotlightTag;
1089
- }
1090
- function notifyStateListeners() {
1091
- stateListeners.forEach(listener => {
1092
- try {
1093
- listener(globalEnabled);
1094
- } catch (error) {
1095
- console.error("[HighlightUpdates] Error in state listener:", error);
1096
- }
1097
- });
1098
- }
1099
- function subscribe(listener) {
1100
- stateListeners.add(listener);
1101
- listener(globalEnabled);
1102
- return () => {
1103
- stateListeners.delete(listener);
1104
- };
1105
- }
1106
- function initialize() {
1107
- if (typeof __DEV__ !== "undefined" && !__DEV__) {
1108
- debugLog("Only available in development builds");
1109
- return false;
1110
- }
1111
- if (initialized) {
1112
- return true;
1113
- }
1114
- hook = window?.__REACT_DEVTOOLS_GLOBAL_HOOK__ || null;
1115
- if (!hook) {
1116
- debugLog("React DevTools hook not found");
1117
- return false;
1118
- }
1119
- debugLog("Hook found");
1120
- debugLog(`Hook has sub: ${typeof hook.sub === "function"}`);
1121
- debugLog(`Hook has on: ${typeof hook.on === "function"}`);
1122
- debugLog(`Hook has emit: ${typeof hook.emit === "function"}`);
1123
-
1124
- // Install profiler interceptor to capture what DevTools detects
1125
- // This allows us to compare profiler data with our detection
1126
- (0, _ProfilerInterceptor.installProfilerInterceptor)();
1127
-
1128
- // Comparison callback available for future use when we re-enable our implementation
1129
- // setComparisonCallback((profilerNodes: Set<unknown>) => {
1130
- // debugLog(`[COMPARISON] Profiler detected ${profilerNodes.size} nodes`);
1131
- // });
1132
-
1133
- if (hook.rendererInterfaces && hook.rendererInterfaces.size > 0) {
1134
- initialized = true;
1135
- debugLog(`Initialized with ${hook.rendererInterfaces.size} renderer(s)`);
1136
- exposeGlobally();
1137
- return true;
1138
- }
1139
-
1140
- // Wait for renderer to be available
1141
- const checkInterval = setInterval(() => {
1142
- if (hook?.rendererInterfaces && hook.rendererInterfaces.size > 0) {
1143
- clearInterval(checkInterval);
1144
- initialized = true;
1145
- debugLog(`Initialized with ${hook.rendererInterfaces.size} renderer(s) (delayed)`);
1146
- exposeGlobally();
1147
- }
1148
- }, 100);
1149
- setTimeout(() => clearInterval(checkInterval), 10000);
1150
- return false;
1151
- }
1152
- function exposeGlobally() {
1153
- if (typeof window !== "undefined") {
1154
- window.__HIGHLIGHT_UPDATES_CONTROLLER__ = {
1155
- enable,
1156
- disable,
1157
- toggle,
1158
- isEnabled,
1159
- setEnabled,
1160
- subscribe,
1161
- initialize,
1162
- destroy,
1163
- isInitialized: () => initialized,
1164
- setHighlightCallback
1165
- };
1166
- }
1167
- }
1168
- function enable() {
1169
- if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1170
- if (!initialized) {
1171
- initialize();
1172
- }
1173
- if (globalEnabled) {
1174
- return;
1175
- }
1176
- debugLog("Enabling highlights");
1177
-
1178
- // Only subscribe if not already subscribed via background tracking
1179
- if (!backgroundTrackingEnabled) {
1180
- subscribeToTraceUpdates();
1181
- }
1182
-
1183
- // Start tracking renders
1184
- _RenderTracker.RenderTracker.start();
1185
-
1186
- // Note: profiler logging disabled for normal operation
1187
- // enableProfilerLogging();
1188
-
1189
- globalEnabled = true;
1190
- notifyStateListeners();
1191
- (0, _sharedUi.notifySubscriberCountChange)('render');
1192
- }
1193
- function disable() {
1194
- if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1195
- if (!globalEnabled) {
1196
- return;
1197
- }
1198
- debugLog("Disabling highlights");
1199
-
1200
- // Clear any pending locks/state
1201
- renderingLock = false;
1202
- isProcessing = false;
1203
- if (renderingLockTimeout) {
1204
- clearTimeout(renderingLockTimeout);
1205
- renderingLockTimeout = null;
1206
- }
1207
- renderedOverlayTags.clear();
1208
- devToolsNodeCache.clear(); // Clear detection cache
1209
- (0, _RenderCauseDetector.clearRenderCauseState)(); // Clear render cause state to prevent memory leaks
1210
-
1211
- // Only unsubscribe if background tracking doesn't need it
1212
- if (!backgroundTrackingEnabled) {
1213
- unsubscribeFromTraceUpdates();
1214
- }
1215
-
1216
- // Stop tracking renders
1217
- _RenderTracker.RenderTracker.stop();
1218
-
1219
- // Note: profiler logging disabled for normal operation
1220
- // disableProfilerLogging();
1221
-
1222
- globalEnabled = false;
1223
- notifyStateListeners();
1224
- (0, _sharedUi.notifySubscriberCountChange)('render');
1225
- }
1226
-
1227
- /**
1228
- * Enable background render tracking (for Events tool).
1229
- * This enables render interception WITHOUT affecting the visual toggle state.
1230
- * The visual highlight toggle remains independent.
1231
- */
1232
- function enableBackgroundTracking() {
1233
- if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1234
- if (backgroundTrackingEnabled) {
1235
- return;
1236
- }
1237
- if (!initialized) {
1238
- initialize();
1239
- }
1240
- debugLog("Enabling background tracking");
1241
-
1242
- // Only subscribe if not already subscribed via main toggle
1243
- if (!globalEnabled) {
1244
- subscribeToTraceUpdates();
1245
- }
1246
- backgroundTrackingEnabled = true;
1247
- }
1248
-
1249
- /**
1250
- * Disable background render tracking (for Events tool).
1251
- * Only actually unsubscribes if the main toggle is also off.
1252
- */
1253
- function disableBackgroundTracking() {
1254
- if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1255
- if (!backgroundTrackingEnabled) {
1256
- return;
1257
- }
1258
- debugLog("Disabling background tracking");
1259
- backgroundTrackingEnabled = false;
1260
-
1261
- // Only unsubscribe if main toggle is also off
1262
- if (!globalEnabled) {
1263
- unsubscribeFromTraceUpdates();
1264
- }
1265
- }
1266
-
1267
- /**
1268
- * Check if background tracking is enabled (for debugging)
1269
- */
1270
- function isBackgroundTrackingEnabled() {
1271
- return backgroundTrackingEnabled;
1272
- }
1273
- function toggle() {
1274
- if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1275
- if (globalEnabled) {
1276
- disable();
1277
- } else {
1278
- enable();
1279
- }
1280
- }
1281
-
1282
- /**
1283
- * Clear all render counts and tracked data
1284
- */
1285
- function clearRenderCounts() {
1286
- nodeRenderCounts.clear();
1287
- _RenderTracker.RenderTracker.clear();
1288
- debugLog("Cleared render counts");
1289
- }
1290
- function isEnabled() {
1291
- return globalEnabled;
1292
- }
1293
- function setEnabled(enabled) {
1294
- if (enabled) enable();else disable();
1295
- }
1296
- function isInitialized() {
1297
- return initialized;
1298
- }
1299
-
1300
- // ============================================================================
1301
- // FREEZE FRAME MODE
1302
- // ============================================================================
1303
-
1304
- /**
1305
- * Notify all freeze state listeners of a change
1306
- */
1307
- function notifyFreezeListeners() {
1308
- freezeListeners.forEach(listener => {
1309
- try {
1310
- listener(isFrozen);
1311
- } catch (error) {
1312
- console.error("[HighlightUpdates] Error in freeze listener:", error);
1313
- }
1314
- });
1315
- }
1316
-
1317
- /**
1318
- * Subscribe to freeze state changes
1319
- */
1320
- function subscribeToFreeze(listener) {
1321
- freezeListeners.add(listener);
1322
- listener(isFrozen);
1323
- return () => {
1324
- freezeListeners.delete(listener);
1325
- };
1326
- }
1327
-
1328
- /**
1329
- * Freeze highlights - prevents highlights from fading away.
1330
- * New renders are still captured but old highlights don't clear.
1331
- */
1332
- function freeze() {
1333
- if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1334
- if (isFrozen) return;
1335
- isFrozen = true;
1336
- debugLog("Freeze mode enabled");
1337
- notifyFreezeListeners();
1338
- }
1339
-
1340
- /**
1341
- * Unfreeze highlights - resumes normal cleanup behavior.
1342
- * Clears all current highlights when unfreezing.
1343
- */
1344
- function unfreeze() {
1345
- if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1346
- if (!isFrozen) return;
1347
- isFrozen = false;
1348
- debugLog("Freeze mode disabled");
1349
-
1350
- // Clear all current highlights when unfreezing
1351
- if (highlightCallback) {
1352
- highlightCallback([]);
1353
- }
1354
- notifyFreezeListeners();
1355
- }
1356
-
1357
- /**
1358
- * Toggle freeze state
1359
- */
1360
- function toggleFreeze() {
1361
- if (isFrozen) {
1362
- unfreeze();
1363
- } else {
1364
- freeze();
1365
- }
1366
- }
1367
-
1368
- /**
1369
- * Check if freeze mode is active
1370
- */
1371
- function getFrozen() {
1372
- return isFrozen;
1373
- }
1374
- function destroy() {
1375
- if (!initialized) return;
1376
- unsubscribeFromTraceUpdates();
1377
-
1378
- // Uninstall profiler interceptor
1379
- (0, _ProfilerInterceptor.uninstallProfilerInterceptor)();
1380
- (0, _ProfilerInterceptor.setComparisonCallback)(null);
1381
-
1382
- // Reset freeze state
1383
- isFrozen = false;
1384
- freezeListeners.clear();
1385
- globalEnabled = false;
1386
- hook = null;
1387
- highlightCallback = null;
1388
- initialized = false;
1389
- if (typeof window !== "undefined") {
1390
- delete window.__HIGHLIGHT_UPDATES_CONTROLLER__;
1391
- }
1392
- debugLog("Destroyed");
1393
- }
1394
- const HighlightUpdatesController = {
1395
- subscribe,
1396
- enable,
1397
- disable,
1398
- toggle,
1399
- isEnabled,
1400
- setEnabled,
1401
- initialize,
1402
- destroy,
1403
- isInitialized,
1404
- setHighlightCallback,
1405
- clearRenderCounts,
1406
- // Freeze frame mode
1407
- freeze,
1408
- unfreeze,
1409
- toggleFreeze,
1410
- getFrozen,
1411
- subscribeToFreeze,
1412
- // Badge press callback for "Click Overlay Badge → Jump to Detail"
1413
- setBadgePressCallback,
1414
- getBadgePressCallback,
1415
- handleBadgePress,
1416
- // Spotlight highlight for detail view
1417
- setSpotlightCallback,
1418
- setSpotlight,
1419
- getSpotlight,
1420
- // Cache management for excludeDevTools toggle
1421
- clearDevToolsCache,
1422
- // Background tracking for Events tool (separate from visual toggle)
1423
- enableBackgroundTracking,
1424
- disableBackgroundTracking,
1425
- isBackgroundTrackingEnabled
1426
- };
1427
- var _default = exports.default = HighlightUpdatesController;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _ProfilerInterceptor=require("./ProfilerInterceptor"),_RenderTracker=require("./RenderTracker"),_PerformanceLogger=require("./PerformanceLogger"),_RenderCauseDetector=require("./RenderCauseDetector"),_sharedUi=require("@buoy-gg/shared-ui");let globalEnabled=!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,n){}function getPublicInstance(e){if(!e)return null;const n=e;return n.canonical?.publicInstance?n.canonical.publicInstance:n.canonical&&"function"==typeof n.canonical.measure?n.canonical:"function"==typeof n.measure?n:null}function getNativeTag(e){if(null==e)return null;const n=e;if(null!=n.__nativeTag)return n.__nativeTag;if(null!=n._nativeTag)return n._nativeTag;if(null!=n.nativeTag)return n.nativeTag;if(n.canonical){if(null!=n.canonical.__nativeTag)return n.canonical.__nativeTag;if(null!=n.canonical._nativeTag)return n.canonical._nativeTag}return null}function extractComponentInfo(e){const n=e,t={viewType:"Unknown"};n?.canonical?.viewConfig?.uiViewClassName?t.viewType=n.canonical.viewConfig.uiViewClassName:n?.viewConfig?.uiViewClassName&&(t.viewType=n.viewConfig.uiViewClassName);const r=n?.canonical?.internalInstanceHandle||n?._internalInstanceHandle||n?._internalFiberInstanceHandleDEV,i=n?.canonical?.currentProps,a=n?.canonical?.pendingProps,o=r?.pendingProps,s=r?.memoizedProps;return t.testID=i?.testID||a?.testID||o?.testID||s?.testID||void 0,t.nativeID=i?.nativeID||a?.nativeID||o?.nativeID||s?.nativeID||void 0,t.accessibilityLabel=i?.accessibilityLabel||a?.accessibilityLabel||o?.accessibilityLabel||s?.accessibilityLabel||void 0,t.componentName=getOwningComponentName(r)||void 0,t}function describeNodeForLog(e){const n=e,t=getPublicInstance(e),r={nativeTag:(getNativeTag(e)||getNativeTag(t))??"unknown",type:n?.canonical?"Fabric":"Legacy",hasMeasure:"function"==typeof t?.measure};if(n){if(r.stateNodeKeys=Object.keys(n).slice(0,20),n.node&&(r.nodeKeys=Object.keys(n.node).slice(0,20)),n.viewConfig&&(r.viewConfig={uiViewClassName:n.viewConfig.uiViewClassName,validAttributes:n.viewConfig.validAttributes?Object.keys(n.viewConfig.validAttributes).slice(0,10):void 0}),n.canonical){const e=n.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 n=e.internalInstanceHandle;if(r.fiberKeys=Object.keys(n).slice(0,30),n.type&&(r.fiberType="function"==typeof n.type?n.type.name||n.type.displayName||"function":n.type),n.elementType&&(r.fiberElementType="function"==typeof n.elementType?n.elementType.name||n.elementType.displayName||"function":n.elementType),n._debugOwner){const e=n._debugOwner;r.fiberDebugOwner=e.type?.name||e.type?.displayName||e.elementType?.name||"unknown"}n._debugSource&&(r.fiberDebugSource=n._debugSource),null!=n.tag&&(r.fiberTag=n.tag),n.pendingProps&&(n.pendingProps.nativeID&&(r.fiberPendingNativeID=n.pendingProps.nativeID),n.pendingProps.testID&&(r.fiberPendingTestID=n.pendingProps.testID)),n.memoizedProps&&(n.memoizedProps.nativeID&&(r.fiberMemoizedNativeID=n.memoizedProps.nativeID),n.memoizedProps.testID&&(r.fiberMemoizedTestID=n.memoizedProps.testID))}if(e.publicInstance){const n=e.publicInstance;r.publicInstanceKeys=Object.keys(n).slice(0,20),null!=n.nativeID&&(r.nativeID=n.nativeID),null!=n._nativeID&&(r._nativeID=n._nativeID),n.props&&(r.publicInstanceProps=Object.keys(n.props).slice(0,15),n.props.nativeID&&(r.propsNativeID=n.props.nativeID),n.props.testID&&(r.propsTestID=n.props.testID),n.props.accessibilityLabel&&(r.accessibilityLabel=n.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(n._debugOwner){const e=n._debugOwner;r.debugOwnerType=e.type?.name||e.type?.displayName||typeof e.type}n._debugSource&&(r.debugSource=n._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_COMPONENTS=new Set(["HighlightUpdatesOverlay","HighlightUpdatesModal","HighlightFilterView","RenderDetailView","RenderListItem","RenderListItemInner","RenderHistoryViewer","RenderHistoryFooter","RenderCauseBadge","TwoLevelCauseBadge","EnhancedCauseDisplay","IsolatedRenderList","IsolatedRenderListInner","StatsDisplay","StatsDisplayInner","CurrentStateView","EventStepperFooter","EventsModal","UnifiedEventList","UnifiedEventItem","UnifiedEventDetail","UnifiedEventFilters","UnifiedEventViewer","ReactQueryEventDetail","EventsCopySettingsView"]),HIGHLIGHT_OVERLAY_NATIVE_IDS=new Set(["highlight-updates-overlay","__rn_buoy__highlight-modal"]),HIGHLIGHT_OVERLAY_PREFIXES=["HighlightUpdates","RenderList","RenderDetail","RenderHistory","RenderCause","EventStepper","UnifiedEvent","EventsModal","EventsCopy"],OTHER_DEV_TOOLS_COMPONENTS=new Set(["JsModalComponent","JsModal","TypePicker","PatternInput","PatternChip","DetectedItemsSection","DetectedCategoryBadge","IdentifierBadge","CategoryBadge","AppRenderer","AppOverlay","FloatingTools","DialDevTools","DevToolsVisibilityProvider","AppHostProvider","MinimizedToolsProvider","ModalHeader","TabSelector","SectionHeader","DraggableHeader","WindowControls","TreeDiffViewer","DataViewer","SplitDiffViewer","VirtualizedDataExplorer","DiffSummary","TypeLegend","IndentGuides","IndentGuidesOverlay","CyberpunkInput","DiffView","AnswerCard","DetailsSection","DetailRow","QuickActionsSection","FilterOptionCard","SearchSection","SearchSectionInner","HeaderActions","HeaderActionsInner","MainListHeader","FilterViewHeader","DetailViewHeader","FloatingMenu","FloatingDevTools","MinimizedToolsStack","MinimizedToolsContext","GlitchToolButton","ExpandablePopover","CollapsedPeek","ExpandedWrapper","DialIcon","DialMenu","DialIconItem","OnboardingTooltip","MenuLauncherIcon","DevToolsSettingsModal","SettingsModal","ToolCard","ToolIcon","GripVerticalIcon","UserStatus","Divider","ChevronDown","ChevronUp","ChevronLeft","ChevronRight","ChevronDownIcon","ChevronUpIcon","ChevronLeftIcon","ChevronRightIcon","LogBox","LogBoxLog","LogBoxLogNotification","LogBoxNotificationContainer","_LogBoxNotificationContainer","LogBoxInspector","LogBoxInspectorContainer","LogBoxInspectorHeader","LogBoxInspectorBody","LogBoxInspectorFooter","LogBoxInspectorMessageHeader","LogBoxInspectorStackFrame","LogBoxInspectorSection","LogBoxButton","LogBoxMessage"]),OTHER_DEV_TOOLS_PREFIXES=["JsModal","TreeDiff","DataViewer","DiffView","DiffSummary","Virtualized","Floating","Minimized","Dial","Expandable","Chevron","Glitch","Settings","Onboarding","DevTools"],OTHER_DEV_TOOLS_NATIVE_IDS=new Set(["jsmodal-root","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 n=e.charCodeAt(0);return!(95!==n||!e.startsWith("__rn_buoy__"))||!(108!==n||!e.startsWith("logbox"))}function getComponentName(e){if(!e)return null;const n=e.type;if(n){if("string"==typeof n)return n;if(n.name)return n.name;if(n.displayName)return n.displayName}const t=e.elementType;if(t){if(t.name)return t.name;if(t.displayName)return t.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 n=e._debugOwner||e.return,t=0,r=null;for(;n&&t<30;){const e=getComponentName(n);if(e&&"string"!=typeof n.type&&(r||(r=e),!isInternalComponent(e)))return e;n=n.return,t++}return r}function isOurOverlayNode(e){const n=e,t=n?.canonical?.internalInstanceHandle||n?._internalInstanceHandle||n?._internalFiberInstanceHandleDEV,r=getNativeTag(e)||getNativeTag(n?.canonical?.publicInstance),i=_RenderTracker.RenderTracker.getSettings().excludeDevTools;if(null!=r&&i){const e=devToolsNodeCache.get(r);if(void 0!==e)return e}let a=!1;const o=t?.pendingProps?.nativeID||t?.memoizedProps?.nativeID||n?.canonical?.currentProps?.nativeID||null;if((isHighlightOverlayNativeID(o)||i&&isOtherDevToolsNativeID(o))&&(a=!0),!a&&t){let e=t,n=0;for(;e&&n<30;){const t=getComponentName(e);if(t){if(HIGHLIGHT_OVERLAY_COMPONENTS.has(t)){a=!0;break}for(const e of HIGHLIGHT_OVERLAY_PREFIXES)if(t.startsWith(e)){a=!0;break}if(a)break;if(i){if(OTHER_DEV_TOOLS_COMPONENTS.has(t)){a=!0;break}for(const e of OTHER_DEV_TOOLS_PREFIXES)if(t.startsWith(e)){a=!0;break}if(a)break}}const r=e.pendingProps?.nativeID||e.memoizedProps?.nativeID;if(isHighlightOverlayNativeID(r)){a=!0;break}if(i&&isOtherDevToolsNativeID(r)){a=!0;break}e=e.return,n++}}if(a&&null!=r&&i){if(devToolsNodeCache.size>=500){const e=Array.from(devToolsNodeCache.keys());for(let n=0;n<250;n++)devToolsNodeCache.delete(e[n])}devToolsNodeCache.set(r,a)}return a}function getColorForRenderCount(e){const n=Math.min(e-1,COLORS.length-1);return COLORS[Math.max(0,n)]}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 n=_RenderTracker.RenderTracker.getBatchSize(),t=_PerformanceLogger.PerformanceLogger.startBatch(e.size,n),r=[];let i=0,a=0;const o=_RenderTracker.RenderTracker.hasActiveFilters();for(const n of e)if(n&&"object"==typeof n){if(isOurOverlayNode(n)){i++;continue}const e=getPublicInstance(n),t=getNativeTag(n)||getNativeTag(e);if(null==t)continue;const s=extractComponentInfo(n);if(o&&!_RenderTracker.RenderTracker.passesFilters(s)){a++;continue}let l,c;_RenderTracker.RenderTracker.getSettings().showRenderCount?(l=(nodeRenderCounts.get(t)||0)+1,nodeRenderCounts.set(t,l),c=getColorForRenderCount(l)):(l=0,c=COLORS[0]),r.push({node:n,color:c,count:l})}if(t.markFilteringComplete(i+a,r.length),0===r.length)return void t.finish();const s=_RenderTracker.RenderTracker.getRenderEventCallbackCount()>0;if(!highlightCallback&&!s)return void(isProcessing=!1);t.markMeasurementStart();const l=r.slice(0,n).map(({node:e,color:n,count:t})=>new Promise(r=>{const i=getPublicInstance(e);if(!i)return void r({rect:null,stateNode:e,color:n,count:t});const a=getNativeTag(e)||getNativeTag(i);if(null!=a)try{i.measure((i,o,s,l,c,d)=>{r(null!=c&&null!=d&&null!=s&&null!=l?{rect:{id:a,x:c,y:d,width:s,height:l,color:n,count:t},stateNode:e,color:n,count:t}:{rect:null,stateNode:e,color:n,count:t})})}catch(i){r({rect:null,stateNode:e,color:n,count:t})}else r({rect:null,stateNode:e,color:n,count:t})}));Promise.all(l).then(e=>{const n=e.filter(e=>null!==e.rect),r=n.map(e=>e.rect);t.markMeasurementComplete(n.length,e.length-n.length);const i=_RenderTracker.RenderTracker.getSettings(),a=i.trackRenderCauses&&i.showRenderCount;let o=null;if(a){o=new Set;for(const{rect:e}of n)e&&o.add(e.id)}if(globalEnabled){_RenderTracker.RenderTracker.startBatch();for(const{rect:e,stateNode:t,color:r,count:s}of n)if(e){const n=extractComponentInfo(t);let l;if(a&&o){const n=t,r=n?.canonical?.internalInstanceHandle;l=(0,_RenderCauseDetector.detectRenderCause)(e.id,r,o,i.debugLogLevel)}_RenderTracker.RenderTracker.trackRender({nativeTag:e.id,viewType:n.viewType,testID:n.testID,nativeID:n.nativeID,accessibilityLabel:n.accessibilityLabel,componentName:n.componentName,measurements:{x:e.x,y:e.y,width:e.width,height:e.height},color:r,count:s,renderCause:l})}_RenderTracker.RenderTracker.endBatch()}else for(const{rect:e,stateNode:t,color:r,count:s}of n)if(e){const n=extractComponentInfo(t);let l;if(a&&o){const n=t,r=n?.canonical?.internalInstanceHandle;l=(0,_RenderCauseDetector.detectRenderCause)(e.id,r,o,i.debugLogLevel)}_RenderTracker.RenderTracker.emitRenderEvent({nativeTag:e.id,viewType:n.viewType,testID:n.testID,nativeID:n.nativeID,accessibilityLabel:n.accessibilityLabel,componentName:n.componentName,measurements:{x:e.x,y:e.y,width:e.width,height:e.height},color:r,count:s,renderCause:l})}t.markTrackingComplete(),r.length>0&&highlightCallback&&globalEnabled&&highlightCallback(r),t.markCallbackComplete(),t.finish()}).catch(e=>{console.error("[HighlightUpdates] Error in measurement pipeline:",e),t.finish()})}function setTraceUpdatesOnRenderers(e){if(!hook?.rendererInterfaces)return void debugLog("No rendererInterfaces available");let n=0;if(hook.rendererInterfaces.forEach((t,r)=>{if("function"==typeof t.setTraceUpdatesEnabled)try{t.setTraceUpdatesEnabled(e),n++,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 ${n} 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){currentSpotlightTag=e,spotlightCallback&&spotlightCallback(e)}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(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(),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)(),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__)&&(globalEnabled?disable():enable())}function clearRenderCounts(){nodeRenderCounts.clear(),_RenderTracker.RenderTracker.clear(),debugLog("Cleared render counts")}function isEnabled(){return globalEnabled}function setEnabled(e){e?enable():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(){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};var _default=exports.default=HighlightUpdatesController;