Commit d1226874 authored by Jiachi Liu's avatar Jiachi Liu

refactor into devtool

parent ae18e3db
.suspense-profiler {
display: flex;
flex-direction: column;
height: 100%;
font-size: var(--size-14);
}
.suspense-profiler-header {
display: flex;
align-items: center;
padding: 14px 16px;
background-color: var(--color-background-200);
gap: 12px;
border-bottom: 1px solid var(--color-gray-400);
}
.suspense-profiler-header-title {
font-size: var(--size-14);
font-weight: 500;
color: var(--color-gray-1000);
line-height: 20px;
}
.suspense-profiler-stats {
display: flex;
gap: 12px;
margin-left: auto;
}
.suspense-profiler-stat {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: var(--size-12);
color: var(--color-gray-800);
}
.suspense-profiler-stat-value {
font-weight: 600;
color: var(--color-gray-1000);
}
.suspense-profiler-content {
flex: 1;
overflow: auto;
padding: 8px 0;
}
.suspense-profiler-empty {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
color: var(--color-gray-800);
font-size: var(--size-14);
}
.suspense-profiler-node-row {
display: flex;
align-items: center;
padding: 8px 12px;
gap: 8px;
cursor: pointer;
transition: background-color 0.15s ease;
}
.suspense-profiler-node-row:hover {
background-color: var(--color-background-200);
}
.suspense-profiler-toggle {
width: 12px;
color: var(--color-gray-700);
font-size: 10px;
flex-shrink: 0;
}
.suspense-profiler-toggle-placeholder {
width: 12px;
flex-shrink: 0;
}
.suspense-profiler-name {
font-weight: 500;
color: var(--color-gray-1000);
}
.suspense-profiler-badge {
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: 12px;
font-size: var(--size-11);
font-weight: 500;
}
.suspense-profiler-badge--suspense {
background-color: var(--color-blue-300);
color: var(--color-blue-900);
}
.suspense-profiler-status {
margin-left: auto;
font-size: var(--size-12);
color: var(--color-gray-700);
}
.suspense-profiler-status--ok {
color: var(--color-green-900);
}
.suspense-profiler-insights-btn {
margin-left: auto;
padding: 4px 10px;
background: var(--color-background-100);
border: 1px solid var(--color-gray-400);
border-radius: 4px;
font-size: var(--size-12);
color: var(--color-gray-1000);
cursor: pointer;
transition: background-color 0.15s ease;
}
.suspense-profiler-insights-btn:hover {
background: var(--color-gray-200);
}
/* Dynamic API row */
.suspense-profiler-api-row {
display: flex;
align-items: center;
padding: 6px 12px;
gap: 8px;
}
.suspense-profiler-api-code {
font-family: var(--font-mono);
font-size: var(--size-12);
background: var(--color-gray-200);
padding: 2px 6px;
border-radius: 4px;
color: var(--color-gray-1000);
}
.suspense-profiler-collapse-btn {
width: 16px;
height: 16px;
padding: 0;
background: var(--color-gray-200);
border: none;
border-radius: 4px;
font-size: var(--size-12);
color: var(--color-gray-700);
cursor: pointer;
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.suspense-profiler-collapse-btn:hover {
background: var(--color-gray-300);
}
.suspense-profiler-collapse-placeholder {
width: 16px;
flex-shrink: 0;
}
.suspense-profiler-layers-badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 16px;
height: 16px;
padding: 0 4px;
margin-left: 6px;
font-size: var(--size-11);
font-weight: 600;
color: var(--color-amber-900);
background: var(--color-amber-200);
border-radius: 8px;
}
/* Component trace */
.suspense-profiler-trace {
padding: 4px 12px 8px;
}
.suspense-profiler-trace-item {
font-size: var(--size-12);
color: var(--color-gray-700);
padding: 2px 0;
font-family: var(--font-mono);
}
.suspense-profiler-trace-item::before {
content: '└ ';
color: var(--color-gray-500);
}
/* Modal */
.suspense-profiler-modal-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 100000;
}
.suspense-profiler-modal {
background: var(--color-background-100);
padding: 16px;
border-radius: 8px;
max-width: 500px;
max-height: 80vh;
overflow: auto;
font-size: var(--size-13);
white-space: pre-wrap;
color: var(--color-gray-1000);
border: 1px solid var(--color-gray-400);
}
.suspense-profiler-modal-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
padding-bottom: 12px;
border-bottom: 1px solid var(--color-gray-400);
}
.suspense-profiler-modal-title {
font-weight: 600;
font-size: var(--size-14);
}
.suspense-profiler-modal-close {
background: none;
border: none;
font-size: 18px;
cursor: pointer;
color: var(--color-gray-700);
padding: 0 4px;
line-height: 1;
}
.suspense-profiler-modal-close:hover {
color: var(--color-gray-1000);
}
.suspense-profiler-modal-content {
font-family: var(--font-mono);
font-size: var(--size-12);
line-height: 1.5;
}
.suspense-profiler-modal-copy {
margin-top: 12px;
padding: 8px 16px;
background: var(--color-gray-1000);
color: var(--color-background-100);
border: none;
border-radius: 6px;
font-size: var(--size-14);
font-weight: 500;
cursor: pointer;
width: 100%;
}
.suspense-profiler-modal-copy:hover {
opacity: 0.9;
}
import './suspense-profiler.css'
import { useState, useMemo, useCallback } from 'react'
import type {
SuspenseBoundaryData,
SuspenseBoundaryInfo,
DynamicAPIAccess,
} from '../../../../server/app-render/suspense-boundary-injector'
// Read suspense boundary data from the DOM (injected by server)
function getSuspenseDataFromDOM(): SuspenseBoundaryData | null {
if (typeof document === 'undefined') return null
const script = document.getElementById('__NEXT_SUSPENSE_BOUNDARIES__')
if (!script) return null
try {
return JSON.parse(script.textContent || '{}')
} catch {
return null
}
}
interface DynamicReason {
expression: string
layersBetween: number
componentsBetween: string[]
}
function matchDynamicToBoundary(
boundaries: SuspenseBoundaryInfo[],
dynamicAccesses: DynamicAPIAccess[]
): Record<string, DynamicReason[]> {
const boundaryReasons: Record<string, DynamicReason[]> = {}
dynamicAccesses.forEach((api) => {
if (!api.frames.length) return
const apiFrames = api.frames.slice().reverse()
const apiNames = apiFrames.map((f) => f.componentName)
let bestMatch: string | null = null
let bestMatchLen = 0
let bestBoundaryLen = 0
boundaries.forEach((b) => {
if (!b.frames.length) return
const boundaryFrames = b.frames.slice().reverse()
const boundaryNames = boundaryFrames.map((f) => f.componentName)
if (boundaryNames.length > apiNames.length) return
let isPrefix = true
for (let i = 0; i < boundaryNames.length; i++) {
if (boundaryNames[i] !== apiNames[i]) {
isPrefix = false
break
}
}
if (isPrefix && boundaryNames.length > bestMatchLen) {
bestMatch = b.id
bestMatchLen = boundaryNames.length
bestBoundaryLen = boundaryNames.length
}
})
if (bestMatch) {
const layersBetween = apiNames.length - bestBoundaryLen
const componentsBetween = apiNames.slice(bestBoundaryLen)
if (!boundaryReasons[bestMatch]) boundaryReasons[bestMatch] = []
// Dedupe by expression + trace path
const traceKey = componentsBetween.join('>')
const exists = boundaryReasons[bestMatch].some(
(r) =>
r.expression === api.expression &&
r.componentsBetween.join('>') === traceKey
)
if (!exists) {
boundaryReasons[bestMatch].push({
expression: api.expression,
layersBetween,
componentsBetween,
})
}
}
})
return boundaryReasons
}
function generatePrompt(
suspenseComponent: string,
reasons: DynamicReason[]
): string | null {
const deepReasons = reasons.filter((r) => r.layersBetween > 0)
if (deepReasons.length === 0) return null
let prompt = `I have a React component structure where a Suspense boundary in "${suspenseComponent}" wraps dynamic API calls that are nested deep in the component tree. This causes more content than necessary to show loading states.\n\n`
prompt += 'Current structure:\n'
for (const r of deepReasons) {
prompt += `- ${r.expression}() is called ${r.layersBetween} layers deep: ${r.componentsBetween.join(' > ')}\n`
}
prompt +=
'\nPlease help me move the Suspense boundary closer to the dynamic API calls to minimize the loading state area. Show me the refactored code.'
return prompt
}
function DynamicAPIRow({
reason,
depth,
expandedTraces,
onToggleTrace,
}: {
reason: DynamicReason
depth: number
expandedTraces: Record<string, boolean>
onToggleTrace: (key: string) => void
}) {
const traceKey = `${reason.expression}-${reason.componentsBetween.join('-')}`
const isTraceExpanded = expandedTraces[traceKey]
const hasNestedLayers = reason.layersBetween > 0
return (
<div>
<div
className="suspense-profiler-api-row"
style={{ paddingLeft: `${12 + depth * 16}px` }}
>
{hasNestedLayers ? (
<button
className="suspense-profiler-collapse-btn"
onClick={() => onToggleTrace(traceKey)}
>
{isTraceExpanded ? '−' : '+'}
</button>
) : (
<span className="suspense-profiler-collapse-placeholder" />
)}
<code className="suspense-profiler-api-code">
{reason.expression}()
{hasNestedLayers && (
<span className="suspense-profiler-layers-badge">
{reason.layersBetween}
</span>
)}
</code>
</div>
{isTraceExpanded && hasNestedLayers && (
<div
className="suspense-profiler-trace"
style={{ paddingLeft: `${12 + depth * 16 + 16}px` }}
>
{reason.componentsBetween.map((comp, i) => (
<div key={i} className="suspense-profiler-trace-item">
{comp}
</div>
))}
</div>
)}
</div>
)
}
function SuspenseBoundaryRow({
boundary,
reasons,
depth,
expanded,
expandedTraces,
onToggle,
onToggleTrace,
onShowInsights,
}: {
boundary: SuspenseBoundaryInfo
reasons: DynamicReason[]
depth: number
expanded: boolean
expandedTraces: Record<string, boolean>
onToggle: () => void
onToggleTrace: (key: string) => void
onShowInsights: (prompt: string) => void
}) {
const componentName =
boundary.frames.length > 0 ? boundary.frames[0].componentName : 'Unknown'
const hasReasons = reasons.length > 0
const deepReasons = reasons.filter((r) => r.layersBetween > 0)
const hasDeepReasons = deepReasons.length > 0
const prompt = generatePrompt(componentName, reasons)
return (
<div>
<div
className="suspense-profiler-node-row"
style={{ paddingLeft: `${12 + depth * 16}px` }}
onClick={onToggle}
>
{hasReasons ? (
<span className="suspense-profiler-toggle">
{expanded ? '▼' : '▶'}
</span>
) : (
<span className="suspense-profiler-toggle-placeholder" />
)}
<span className="suspense-profiler-name">{componentName}</span>
<span className="suspense-profiler-badge suspense-profiler-badge--suspense">
suspense
</span>
{hasReasons && !hasDeepReasons && (
<span className="suspense-profiler-status suspense-profiler-status--ok">
ok
</span>
)}
{prompt && (
<button
className="suspense-profiler-insights-btn"
onClick={(e) => {
e.stopPropagation()
onShowInsights(prompt)
}}
>
insights
</button>
)}
</div>
{expanded &&
reasons.map((reason, i) => (
<DynamicAPIRow
key={i}
reason={reason}
depth={depth + 1}
expandedTraces={expandedTraces}
onToggleTrace={onToggleTrace}
/>
))}
</div>
)
}
function InsightsModal({
prompt,
onClose,
}: {
prompt: string
onClose: () => void
}) {
const [copied, setCopied] = useState(false)
const handleCopy = useCallback(() => {
navigator.clipboard.writeText(prompt).then(() => {
setCopied(true)
setTimeout(() => setCopied(false), 2000)
})
}, [prompt])
return (
<div className="suspense-profiler-modal-overlay" onClick={onClose}>
<div
className="suspense-profiler-modal"
onClick={(e) => e.stopPropagation()}
>
<div className="suspense-profiler-modal-header">
<span className="suspense-profiler-modal-title">
Optimization Suggestion
</span>
<button className="suspense-profiler-modal-close" onClick={onClose}>
×
</button>
</div>
<div className="suspense-profiler-modal-content">{prompt}</div>
<button className="suspense-profiler-modal-copy" onClick={handleCopy}>
{copied ? 'Copied!' : 'Copy to Clipboard'}
</button>
</div>
</div>
)
}
export function SuspenseProfiler() {
const [expanded, setExpanded] = useState<Record<string, boolean>>({})
const [expandedTraces, setExpandedTraces] = useState<Record<string, boolean>>(
{}
)
const [insightsPrompt, setInsightsPrompt] = useState<string | null>(null)
// Read data from DOM on mount
const data = useMemo(() => getSuspenseDataFromDOM(), [])
const boundaries = useMemo(() => data?.boundaries || [], [data?.boundaries])
const dynamicAccesses = useMemo(
() => data?.dynamicAccesses || [],
[data?.dynamicAccesses]
)
// Match all boundaries, then merge reasons by component path
const allBoundaryReasons = useMemo(() => {
return matchDynamicToBoundary(boundaries, dynamicAccesses)
}, [boundaries, dynamicAccesses])
// Deduplicate boundaries by their component stack path, merging reasons
const { uniqueBoundaries, boundaryReasons } = useMemo(() => {
const seen = new Map<
string,
{ boundary: SuspenseBoundaryInfo; reasons: DynamicReason[] }
>()
for (const b of boundaries) {
const key = b.frames.map((f) => f.componentName).join('>')
const reasons = allBoundaryReasons[b.id] || []
if (!seen.has(key)) {
seen.set(key, { boundary: b, reasons: [...reasons] })
} else {
// Merge reasons from duplicate boundaries
const existing = seen.get(key)!
for (const r of reasons) {
const traceKey = r.componentsBetween.join('>')
const exists = existing.reasons.some(
(er) =>
er.expression === r.expression &&
er.componentsBetween.join('>') === traceKey
)
if (!exists) {
existing.reasons.push(r)
}
}
}
}
const result: {
boundary: SuspenseBoundaryInfo
reasons: DynamicReason[]
}[] = []
const reasonsMap: Record<string, DynamicReason[]> = {}
for (const [, entry] of seen) {
result.push(entry)
reasonsMap[entry.boundary.id] = entry.reasons
}
return {
uniqueBoundaries: result.map((e) => e.boundary),
boundaryReasons: reasonsMap,
}
}, [boundaries, allBoundaryReasons])
const handleToggle = useCallback((id: string) => {
setExpanded((prev) => ({
...prev,
[id]: !prev[id],
}))
}, [])
const handleToggleTrace = useCallback((key: string) => {
setExpandedTraces((prev) => ({
...prev,
[key]: !prev[key],
}))
}, [])
const handleShowInsights = useCallback((prompt: string) => {
setInsightsPrompt(prompt)
}, [])
const handleCloseInsights = useCallback(() => {
setInsightsPrompt(null)
}, [])
return (
<div className="suspense-profiler">
<div className="suspense-profiler-header">
<span className="suspense-profiler-header-title">
Suspense Boundaries
</span>
<div className="suspense-profiler-stats">
<span className="suspense-profiler-stat">
<span className="suspense-profiler-stat-value">
{boundaries.length}
</span>{' '}
suspense
</span>
{dynamicAccesses.length > 0 && (
<span className="suspense-profiler-stat">
<span className="suspense-profiler-stat-value">
{dynamicAccesses.length}
</span>{' '}
dynamic
</span>
)}
</div>
</div>
<div className="suspense-profiler-content">
{uniqueBoundaries.length === 0 ? (
<div className="suspense-profiler-empty">No boundaries detected</div>
) : (
uniqueBoundaries.map((boundary) => (
<SuspenseBoundaryRow
key={boundary.id}
boundary={boundary}
reasons={boundaryReasons[boundary.id] || []}
depth={1}
expanded={expanded[boundary.id] ?? true}
expandedTraces={expandedTraces}
onToggle={() => handleToggle(boundary.id)}
onToggleTrace={handleToggleTrace}
onShowInsights={handleShowInsights}
/>
))
)}
</div>
{insightsPrompt && (
<InsightsModal prompt={insightsPrompt} onClose={handleCloseInsights} />
)}
</div>
)
}
...@@ -9,6 +9,7 @@ export type PanelStateKind = ...@@ -9,6 +9,7 @@ export type PanelStateKind =
| 'preferences' | 'preferences'
| 'route-type' | 'route-type'
| 'segment-explorer' | 'segment-explorer'
| 'suspense-profiler'
| 'panel-selector' | 'panel-selector'
export const PanelRouterContext = createContext<{ export const PanelRouterContext = createContext<{
......
...@@ -6,7 +6,14 @@ import { ...@@ -6,7 +6,14 @@ import {
RouteInfoBody, RouteInfoBody,
} from '../components/errors/dev-tools-indicator/dev-tools-info/route-info' } from '../components/errors/dev-tools-indicator/dev-tools-info/route-info'
import { PageSegmentTree } from '../components/overview/segment-explorer' import { PageSegmentTree } from '../components/overview/segment-explorer'
import { SuspenseProfiler } from '../components/overview/suspense-profiler'
import { DevToolsHeader } from '../components/errors/dev-tools-indicator/dev-tools-info/dev-tools-header' import { DevToolsHeader } from '../components/errors/dev-tools-indicator/dev-tools-info/dev-tools-header'
// Check if suspense boundary data exists in the DOM
function hasSuspenseData(): boolean {
if (typeof document === 'undefined') return false
return document.getElementById('__NEXT_SUSPENSE_BOUNDARIES__') !== null
}
import { useDelayedRender } from '../hooks/use-delayed-render' import { useDelayedRender } from '../hooks/use-delayed-render'
import { import {
MENU_CURVE, MENU_CURVE,
...@@ -112,6 +119,16 @@ const MenuPanel = () => { ...@@ -112,6 +119,16 @@ const MenuPanel = () => {
'data-segment-explorer': true, 'data-segment-explorer': true,
}, },
}, },
isAppRouter &&
hasSuspenseData() && {
label: 'Suspense',
title: 'View suspense boundaries and dynamic API calls',
value: <ChevronRight />,
onClick: () => setPanel('suspense-profiler'),
attributes: {
'data-suspense-profiler': true,
},
},
{ {
label: 'Preferences', label: 'Preferences',
value: <GearIcon />, value: <GearIcon />,
...@@ -243,6 +260,30 @@ export const PanelRouter = () => { ...@@ -243,6 +260,30 @@ export const PanelRouter = () => {
</DynamicPanel> </DynamicPanel>
</PanelRoute> </PanelRoute>
)} )}
{isAppRouter && (
<PanelRoute name="suspense-profiler">
<DynamicPanel
sharePanelSizeGlobally={false}
sharePanelPositionGlobally={false}
draggable
sizeConfig={{
kind: 'resizable',
maxHeight: '90vh',
maxWidth: '90vw',
minHeight: 200 / state.scale,
minWidth: 300 / state.scale,
initialSize: {
height: 400 / state.scale,
width: 400 / state.scale,
},
}}
header={<DevToolsHeader title="Suspense Profiler" />}
>
<SuspenseProfiler />
</DynamicPanel>
</PanelRoute>
)}
</> </>
) )
} }
......
...@@ -12,7 +12,6 @@ import { RedirectStatusCode } from '../../client/components/redirect-status-code ...@@ -12,7 +12,6 @@ import { RedirectStatusCode } from '../../client/components/redirect-status-code
import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix' import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix'
import type { ClientTraceDataEntry } from '../lib/trace/tracer' import type { ClientTraceDataEntry } from '../lib/trace/tracer'
import { SuspenseBoundaryScript } from './suspense-boundary-injector' import { SuspenseBoundaryScript } from './suspense-boundary-injector'
import { getSuspenseBoundaries } from './suspense-boundary-collector'
export function makeGetServerInsertedHTML({ export function makeGetServerInsertedHTML({
polyfills, polyfills,
...@@ -28,6 +27,7 @@ export function makeGetServerInsertedHTML({ ...@@ -28,6 +27,7 @@ export function makeGetServerInsertedHTML({
basePath: string basePath: string
}) { }) {
let flushedErrorMetaTagsUntilIndex = 0 let flushedErrorMetaTagsUntilIndex = 0
let suspenseBoundaryScriptFlushed = false
// These only need to be rendered once, they'll be set to empty arrays once flushed. // These only need to be rendered once, they'll be set to empty arrays once flushed.
let polyfillTags = polyfills.map((polyfill) => { let polyfillTags = polyfills.map((polyfill) => {
...@@ -75,21 +75,23 @@ export function makeGetServerInsertedHTML({ ...@@ -75,21 +75,23 @@ export function makeGetServerInsertedHTML({
const serverInsertedHTML = renderServerInsertedHTML() const serverInsertedHTML = renderServerInsertedHTML()
// Suspense boundary script should only be rendered once (on first flush).
// Boundaries are registered during React render, before streaming starts.
const shouldRenderSuspenseScript = !suspenseBoundaryScriptFlushed
if (shouldRenderSuspenseScript) {
suspenseBoundaryScriptFlushed = true
}
// Skip React rendering if we know the content is empty. // Skip React rendering if we know the content is empty.
// Note: We can't skip when suspense profiling might be active since
// SuspenseBoundaryScript may have data to inject.
if ( if (
polyfillTags.length === 0 && polyfillTags.length === 0 &&
traceMetaTags.length === 0 && traceMetaTags.length === 0 &&
errorMetaTags.length === 0 && errorMetaTags.length === 0 &&
!shouldRenderSuspenseScript &&
Array.isArray(serverInsertedHTML) && Array.isArray(serverInsertedHTML) &&
serverInsertedHTML.length === 0 serverInsertedHTML.length === 0
) { ) {
// Check if there are any suspense boundaries to inject return ''
const boundaries = getSuspenseBoundaries()
if (boundaries.length === 0) {
return ''
}
} }
const stream = await renderToReadableStream( const stream = await renderToReadableStream(
...@@ -98,7 +100,7 @@ export function makeGetServerInsertedHTML({ ...@@ -98,7 +100,7 @@ export function makeGetServerInsertedHTML({
{serverInsertedHTML} {serverInsertedHTML}
{traceMetaTags} {traceMetaTags}
{errorMetaTags} {errorMetaTags}
<SuspenseBoundaryScript /> {shouldRenderSuspenseScript && <SuspenseBoundaryScript />}
</>, </>,
{ {
// Larger chunk because this isn't sent over the network. // Larger chunk because this isn't sent over the network.
......
...@@ -4,8 +4,11 @@ import { ...@@ -4,8 +4,11 @@ import {
getDynamicAccesses, getDynamicAccesses,
type SuspenseBoundaryInfo, type SuspenseBoundaryInfo,
type DynamicAPIAccess, type DynamicAPIAccess,
type StackFrame,
} from './suspense-boundary-collector' } from './suspense-boundary-collector'
export type { SuspenseBoundaryInfo, DynamicAPIAccess, StackFrame }
export interface SuspenseBoundaryData { export interface SuspenseBoundaryData {
boundaries: SuspenseBoundaryInfo[] boundaries: SuspenseBoundaryInfo[]
dynamicAccesses: DynamicAPIAccess[] dynamicAccesses: DynamicAPIAccess[]
...@@ -20,321 +23,22 @@ export function getSuspenseBoundaryData(): SuspenseBoundaryData { ...@@ -20,321 +23,22 @@ export function getSuspenseBoundaryData(): SuspenseBoundaryData {
} }
} }
const panelScript = `
(function() {
if (typeof window === 'undefined') return;
function createPanel() {
const script = document.getElementById('__NEXT_SUSPENSE_BOUNDARIES__');
if (!script) return;
let data;
try {
data = JSON.parse(script.textContent || '{}');
} catch (e) {
return;
}
const container = document.createElement('div');
container.id = '__next_suspense_profiler__';
document.body.appendChild(container);
// Track expanded nodes by path
window.__sp = {
isOpen: false,
expanded: {},
prompts: [],
toggle: function(path) {
window.__sp.expanded[path] = !window.__sp.expanded[path];
render();
},
open: function() {
window.__sp.isOpen = true;
render();
},
close: function() {
window.__sp.isOpen = false;
render();
},
showInsights: function(index) {
var prompt = window.__sp.prompts[index];
if (!prompt) return;
navigator.clipboard.writeText(prompt).catch(function() {});
// Show modal with prompt
var overlay = document.createElement('div');
overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:100000;display:flex;align-items:center;justify-content:center;';
overlay.onclick = function(e) { if (e.target === overlay) document.body.removeChild(overlay); };
var modal = document.createElement('div');
modal.style.cssText = 'background:#fff;padding:16px;border-radius:8px;max-width:500px;max-height:80vh;overflow:auto;font-size:13px;white-space:pre-wrap;';
modal.textContent = prompt;
overlay.appendChild(modal);
document.body.appendChild(overlay);
}
};
// Match dynamic accesses to their enclosing suspense boundary
// Returns: { boundaryId -> [{ expression, layersBetween, componentsBetween }] }
function matchDynamicToBoundary(boundaries, dynamicAccesses) {
var boundaryReasons = {};
dynamicAccesses.forEach(function(api) {
if (!api.frames.length) return;
// Frames are leaf-to-root, reverse to get root-to-leaf order
var apiFrames = api.frames.slice().reverse();
var apiNames = apiFrames.map(function(f) { return f.componentName; });
// Find the boundary whose path is a prefix of the api path (nearest ancestor)
var bestMatch = null;
var bestMatchLen = 0;
var bestBoundaryLen = 0;
boundaries.forEach(function(b) {
if (!b.frames.length) return;
var boundaryFrames = b.frames.slice().reverse();
var boundaryNames = boundaryFrames.map(function(f) { return f.componentName; });
// Check if boundary components are a prefix of api components
if (boundaryNames.length > apiNames.length) return;
var isPrefix = true;
for (var i = 0; i < boundaryNames.length; i++) {
if (boundaryNames[i] !== apiNames[i]) {
isPrefix = false;
break;
}
}
if (isPrefix && boundaryNames.length > bestMatchLen) {
bestMatch = b.id;
bestMatchLen = boundaryNames.length;
bestBoundaryLen = boundaryNames.length;
}
});
if (bestMatch) {
// Calculate layers between
var layersBetween = apiNames.length - bestBoundaryLen;
var componentsBetween = apiNames.slice(bestBoundaryLen);
if (!boundaryReasons[bestMatch]) boundaryReasons[bestMatch] = [];
// Check if this expression is already tracked
var exists = false;
for (var i = 0; i < boundaryReasons[bestMatch].length; i++) {
if (boundaryReasons[bestMatch][i].expression === api.expression) {
exists = true;
break;
}
}
if (!exists) {
boundaryReasons[bestMatch].push({
expression: api.expression,
layersBetween: layersBetween,
componentsBetween: componentsBetween
});
}
}
});
return boundaryReasons;
}
// Generate optimization prompt for a suspense boundary with deep dynamic calls
function generatePrompt(suspenseComponent, reasons) {
var deepReasons = [];
for (var i = 0; i < reasons.length; i++) {
if (reasons[i].layersBetween > 0) deepReasons.push(reasons[i]);
}
if (deepReasons.length === 0) return null;
var nl = String.fromCharCode(10);
var prompt = 'I have a React component structure where a Suspense boundary in "' + suspenseComponent + '" wraps dynamic API calls that are nested deep in the component tree. This causes more content than necessary to show loading states.' + nl + nl;
prompt += 'Current structure:' + nl;
for (var j = 0; j < deepReasons.length; j++) {
var r = deepReasons[j];
prompt += '- ' + r.expression + '() is called ' + r.layersBetween + ' layers deep: ' + r.componentsBetween.join(' > ') + nl;
}
prompt += nl + 'Please help me move the Suspense boundary closer to the dynamic API calls to minimize the loading state area. Show me the refactored code.';
var index = window.__sp.prompts.length;
window.__sp.prompts.push(prompt);
return index;
}
// Build tree from boundaries and dynamic accesses
function buildTree(boundaries, dynamicAccesses, boundaryReasons) {
var root = { name: 'Root', children: {}, boundaries: [], apis: [], reasons: [] };
// Add boundaries to tree
boundaries.forEach(function(b) {
if (!b.frames.length) return;
// Reverse frames: from root to leaf
var path = b.frames.slice().reverse();
var node = root;
path.forEach(function(frame) {
var name = frame.componentName;
if (!node.children[name]) {
node.children[name] = { name: name, children: {}, boundaries: [], apis: [], reasons: [], frame: frame };
}
node = node.children[name];
});
node.boundaries.push(b);
// Attach reasons to this boundary node
if (boundaryReasons[b.id]) {
node.reasons = node.reasons.concat(boundaryReasons[b.id]);
}
});
// Add dynamic APIs to tree
dynamicAccesses.forEach(function(api) {
if (!api.frames.length) return;
var path = api.frames.slice().reverse();
var node = root;
path.forEach(function(frame) {
var name = frame.componentName;
if (!node.children[name]) {
node.children[name] = { name: name, children: {}, boundaries: [], apis: [], reasons: [], frame: frame };
}
node = node.children[name];
});
node.apis.push(api);
});
return root;
}
function renderNode(node, depth, path) {
var sp = window.__sp;
var childKeys = Object.keys(node.children);
var hasChildren = childKeys.length > 0;
var hasApi = node.apis && node.apis.length > 0;
var isExpanded = sp.expanded[path] !== false; // Default expanded
var indent = depth * 16;
var html = '';
if (depth > 0) {
var hasSuspense = node.boundaries.length > 0;
var hasReasons = node.reasons && node.reasons.length > 0;
var promptIndex = hasSuspense && hasReasons ? generatePrompt(node.name, node.reasons) : null;
html += '<div style="border-bottom:1px solid #f0f0f0;">';
html += '<div onclick="window.__sp.toggle(\\'' + path + '\\')" style="padding:6px 12px 6px ' + (12 + indent) + 'px;cursor:pointer;display:flex;align-items:center;gap:8px;">';
if (hasChildren || hasApi) {
html += '<span style="color:#999;font-size:9px;width:10px;">' + (isExpanded ? '▼' : '▶') + '</span>';
} else {
html += '<span style="width:10px;"></span>';
}
html += '<span style="color:#333;">' + node.name + '</span>';
if (hasSuspense) {
html += '<span style="background:#eee;color:#666;padding:1px 6px;border-radius:3px;font-size:10px;">suspense</span>';
// Show ok if no deep dynamic calls, or insights button if there are
if (promptIndex !== null) {
html += '<button onclick="event.stopPropagation();window.__sp.showInsights(' + promptIndex + ')" style="background:#f5f5f5;border:1px solid #ddd;color:#333;padding:2px 6px;border-radius:3px;font-size:10px;cursor:pointer;margin-left:auto;">insights</button>';
} else if (hasReasons) {
html += '<span style="color:#666;font-size:11px;margin-left:auto;">ok</span>';
}
}
html += '</div></div>';
}
if (isExpanded) {
// Render dynamic API calls as children
if (hasApi) {
var apiIndent = (depth + 1) * 16;
for (var i = 0; i < node.apis.length; i++) {
var api = node.apis[i];
html += '<div style="border-bottom:1px solid #f0f0f0;">';
html += '<div style="padding:6px 12px 6px ' + (12 + apiIndent) + 'px;display:flex;align-items:center;gap:8px;">';
html += '<span style="width:10px;"></span>';
html += '<code style="background:#f5f5f5;color:#333;padding:1px 4px;border-radius:2px;font-size:11px;">' + api.expression + '</code>';
html += '</div></div>';
}
}
// Render child components
if (hasChildren) {
childKeys.forEach(function(key) {
html += renderNode(node.children[key], depth + 1, path + '/' + key);
});
}
}
return html;
}
function render() {
var boundaries = data.boundaries || [];
var dynamicAccesses = data.dynamicAccesses || [];
var sp = window.__sp;
// Clear prompts array on each render
sp.prompts = [];
if (sp.isOpen) {
var boundaryReasons = matchDynamicToBoundary(boundaries, dynamicAccesses);
var tree = buildTree(boundaries, dynamicAccesses, boundaryReasons);
var treeHtml = '';
Object.keys(tree.children).forEach(function(key) {
treeHtml += renderNode(tree.children[key], 1, key);
});
container.innerHTML = '<div style="position:fixed;bottom:20px;right:20px;z-index:99999;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;font-size:13px;">' +
'<div style="background:#fff;color:#1a1a1a;border:1px solid #e0e0e0;border-radius:8px;width:360px;max-height:450px;overflow:hidden;display:flex;flex-direction:column;box-shadow:0 4px 12px rgba(0,0,0,0.1);">' +
'<div style="padding:12px 16px;border-bottom:1px solid #e0e0e0;display:flex;justify-content:space-between;align-items:center;">' +
'<span style="font-weight:600;color:#1a1a1a;">Component Tree</span>' +
'<button onclick="window.__sp.close()" style="background:none;border:none;color:#666;cursor:pointer;font-size:18px;line-height:1;padding:0 4px;">x</button>' +
'</div>' +
'<div style="overflow:auto;flex:1;">' +
(treeHtml || '<div style="padding:16px;color:#888;">No boundaries detected</div>') +
'</div>' +
'</div>' +
'</div>';
} else {
var hasDynamic = dynamicAccesses.length > 0;
container.innerHTML = '<div style="position:fixed;bottom:20px;right:20px;z-index:99999;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;font-size:13px;">' +
'<button onclick="window.__sp.open()" style="background:#fff;color:#333;border:1px solid #e0e0e0;border-radius:6px;padding:8px 14px;cursor:pointer;display:flex;align-items:center;gap:8px;box-shadow:0 2px 8px rgba(0,0,0,0.08);">' +
'<span>' + boundaries.length + ' suspense</span>' +
(hasDynamic ? '<span style="color:#666;">' + dynamicAccesses.length + ' dynamic</span>' : '') +
'</button>' +
'</div>';
}
}
render();
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', createPanel);
} else {
createPanel();
}
})();
`
export function SuspenseBoundaryScript(): React.ReactNode { export function SuspenseBoundaryScript(): React.ReactNode {
const data = getSuspenseBoundaryData() const data = getSuspenseBoundaryData()
// Only render if there's data to show
if (data.boundaries.length === 0 && data.dynamicAccesses.length === 0) {
return null
}
return ( return (
<> // eslint-disable-next-line @next/internal/no-ambiguous-jsx
<script <script
id="__NEXT_SUSPENSE_BOUNDARIES__" id="__NEXT_SUSPENSE_BOUNDARIES__"
type="application/json" type="application/json"
dangerouslySetInnerHTML={{ dangerouslySetInnerHTML={{
__html: JSON.stringify(data), __html: JSON.stringify(data),
}} }}
/> />
<script
dangerouslySetInnerHTML={{
__html: panelScript,
}}
/>
</>
) )
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment