@buoy-gg/highlight-updates 7.0.38 → 7.0.39

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