Skip to content

Latest commit

 

History

History
478 lines (375 loc) · 17.8 KB

LLD.md

File metadata and controls

478 lines (375 loc) · 17.8 KB

FrameworkX — Low Level Design

1. Entry Point

src/main.tsx

initSWC()   // kick off @swc/wasm-web init immediately — ready before first keystroke
createRoot(document.getElementById('root')!).render(
  <StrictMode><App /></StrictMode>
)

App.tsx is a one-liner that renders <AppShell />. No router — single screen.


2. Shell Layout (src/components/Shell/AppShell.tsx)

┌─────────────────────────────────────────────────────────────────┐
│  Toolbar (header)                                               │
├─────────────────┬───────────────────────────────────────────────┤
│                 │                                               │
│  Monaco Editor  │                                               │
│   (top 60%)     │        VisualizerPanel (70%)                  │
│                 │                                               │
├─────────────────┤                                               │
│  Instrumented   │                                               │
│  Iframe Preview │                                               │
│   (bottom 40%)  │                                               │
└─────────────────┴───────────────────────────────────────────────┘

AppShell mounts useBridge() — the global postMessage listener lives here for the app lifetime.


3. Store Layer

editorStore (src/store/editorStore.ts)

Field Type Description
framework 'react' | 'vue' Active framework
code Record<FrameworkType, string> Per-framework code buffer; survives framework switch
activeExample string | null Reserved for Block 7 preset examples

Starter code:

  • React — multi-component Todo list (Header, AddTodo, TodoItem, TodoList, App)
  • Vue — provide/inject demo with h() render functions (App provides count, doubled, message; CounterSection and MessageSection inject and render them)

bridgeStore (src/store/bridgeStore.ts)

Field Type Description
fiberTree FiberNode | null Latest normalized React fiber tree
vueTree VueComponentNode | null Latest Vue component tree
depGraph DepGraph | null Latest Vue reactivity graph
events InstrumentationEvent[] Ring buffer, max 200 events

clearAll() resets everything — called on framework switch.

visualizerStore (src/store/visualizerStore.ts)

activeTab: 'tree' | 'graph' | 'log' — reserved for Block 7 tabbed panel.


4. Type Contracts (src/types/events.ts)

FiberNode (React)

interface FiberNode {
  id: string                        // stable across commits (ptr-based hash)
  name: string                      // component display name
  type: 'class' | 'function' | 'host' | 'host-text' | 'root' | 'fiber-root'
  depth: number
  renderCount: number               // cumulative — set by adapter, not probe
  renderDuration: number            // ms for this fiber subtree in this commit
  didRerender: boolean              // true if PerformedWork flag was set
  props: Record<string, unknown>    // sanitized (functions → '[Function]')
  state: unknown
  hooks: HookInfo[]
  rerenderedBecause: 'mount' | 'props' | 'state' | 'parent' | null
  changedProps: string[]
  children: FiberNode[]
}

VueComponentNode

interface VueComponentNode {
  id: string                        // String(instance.uid)
  name: string                      // instance.type.__name || .name
  depth: number
  props: Record<string, unknown>
  data: Record<string, unknown>
  children: VueComponentNode[]
  updateCount: number               // cumulative re-renders
  didUpdate: boolean                // true if updated in current emit cycle
  updatedBecause: 'mount' | 'props' | 'data' | 'parent' | null
  changedProps: string[]
}

DepGraph (Vue reactivity)

interface DepNode {
  id: string                        // 'comp-{uid}' or 'dep-{n}'
  type: 'ref' | 'reactive' | 'computed' | 'watchEffect' | 'component'
  name: string                      // variable name from devtoolsRawSetupState
  value?: unknown                   // current reactive value (state nodes only)
  updateCount?: number              // for component nodes
  didUpdate?: boolean
}
interface DepEdge { source: string; target: string; active: boolean }
interface DepGraph { nodes: DepNode[]; edges: DepEdge[] }

postMessage event shapes

Both events are discriminated on source:

  • ReactInstrumentationEvent — source: 'react-probe', payload has fiberTree, renderDuration
  • VueInstrumentationEvent — source: 'vue-probe', payload has componentTree, reactivityGraph

5. Compiler Pipeline

React (src/compiler/swc.ts)

flowchart LR
  TSX["User TSX/TS source"] --> swc["@swc/wasm-web transform()\nparser: typescript+tsx\njsc.target: es2022\nmodule: es6\nreact: automatic runtime"]
  swc --> strip["Strip export default\n3 regex patterns:\nfunction/class/variable"]
  strip --> append["Append\nwindow.dispatchEvent(new CustomEvent('fx:ready',{detail:App}))"]
  append --> esm["Self-contained ESM\nno export default\nfx:ready fires on module eval"]
Loading

initSWC() is a singleton — the WASM binary is fetched once at startup. Subsequent compileReact calls skip init.

Vue (src/compiler/vue.ts)

flowchart LR
  SFC["Vue SFC source"] --> parse["parse()\nproduces descriptor\n{scriptSetup, template, styles}"]
  parse --> cs["compileScript(descriptor, {\n  id,\n  inlineTemplate: false,\n  isProd: false\n})"]
  cs --> bindings["scriptResult.bindings\n{count:'setup-ref', CounterSection:'setup-const', ...}"]
  cs --> content["scriptResult.content\nES module — setup() returns bindings object\nVue sets instance.devtoolsRawSetupState = bindings"]
  parse --> ct["compileTemplate({\n  source: template.content,\n  compilerOptions: { bindingMetadata: bindings }\n})"]
  bindings --> ct
  ct --> render["render function\nuses $setup.CounterSection directly\n(not resolveComponent)"]
  content --> rw["rewriteDefault()\nexport default X → const __vue_sfc__ = X"]
  rw --> out["Combined output:\nscript imports + __vue_sfc__\n+ template imports + function render\n+ __vue_sfc__.render = render\n+ fx:ready dispatch"]
  render --> out
Loading

Why inlineTemplate: false: With inlineTemplate: true, compileScript emits a setup function that returns the render function. Vue's runtime sees isFunction(setupResult) and sets instance.render = fn — it never sets instance.devtoolsRawSetupState. The Vue probe depends on devtoolsRawSetupState to map Dep objects to variable names. With inlineTemplate: false, setup returns the bindings object, Vue sets devtoolsRawSetupState = {count: RefImpl, ...}, and name resolution works.


6. Instrumentation Iframe (src/components/Editor/InstrumentationIframe.tsx)

Shell HTML structure (built by buildShellHtml(framework))

<head>
  <!-- 1. Probe runs first, before any framework code -->
  <script>/* REACT_PROBE_SCRIPT or VUE_PROBE_SCRIPT inlined */</script>

  <!-- 2. Import map tells the module loader where to resolve bare specifiers -->
  <script type="importmap">
    { "imports": { "react": "https://esm.sh/react@19.2.4?dev", ... } }
  </script>

  <!-- 3. Eager module import — fetches and caches CDN deps in module registry -->
  <script type="module">
    import { createRoot } from 'react-dom/client'
    // Listens for fx:update → appends compiled code as new <script type=module>
    // Listens for fx:ready CustomEvent → unmount previous root, mount new component
  </script>
</head>
<body><div id="root"></div></body>

Lifecycle

Framework switch
  → loadedRef = false
  → iframe.srcdoc = buildShellHtml(framework)   // triggers full reload
  → iframe 'load' event
  → loadedRef = true
  → sendUpdate(framework, code)                 // compile + postMessage

Code change (debounced 300ms)
  → if (!loadedRef) return                      // skip if shell not ready
  → sendUpdate(framework, code)
    → compile(framework, code)
    → iframe.contentWindow.postMessage({type:'fx:update', code: compiled})

Refs used to avoid stale closures

codeRef and frameworkRef are kept in sync with the latest values so the async onLoad callback always uses current state.


7. React Probe (src/probes/react-probe.ts)

Injected as an inline <script> in the iframe head. Runs before React loads.

Hook installation

window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
  inject(renderer) {
    // React calls inject() when it registers a renderer
    // Must return a truthy value — React uses it as the rendererID
    return 1
  },
  onCommitFiberRoot(id, root, priorityLevel) {
    // Fires synchronously after every commit (including unmount commits)
    if (!root.current.child) return    // unmount commit — skip
    if (pendingPost) return            // debounce: one post per microtask batch
    pendingPost = setTimeout(() => {
      pendingPost = null
      const tree = buildFiberTree(root.current.child, 0)
      window.parent.postMessage({ source: 'react-probe', type: 'commit', payload: { fiberTree: tree } })
    }, 0)
  }
}

setTimeout(fn, 0) is used instead of requestAnimationFrame because rAF is throttled or skipped in display:none iframes.

Fiber tree walk (buildFiberTree)

Walks fiber.child then fiber.sibling recursively. For each fiber:

  • type is mapped from fiber tag numbers (0=function, 1=class, 3=HostRoot, 5=host, 6=host-text)
  • props are sanitized (functions replaced with '[Function]', circular → '[Circular]')
  • hooks are extracted by walking the memoizedState linked list (.next) and classifying by the hook's internal queue shape
  • didRerender = (fiber.flags & PerformedWork) !== 0 — only fibers that actually ran their render function

postMessage payload

{
  source: 'react-probe',
  type: 'commit',
  timestamp: Date.now(),
  componentId: '<root-id>',
  componentName: '<root-name>',
  payload: {
    fiberTree: FiberNode,     // renderCount=0 here; adapter accumulates it
    renderDuration: number    // ms
  }
}

8. Vue Probe (src/probes/vue-probe.ts)

Injected as an inline <script> in the iframe head. Runs before Vue loads.

Hook installation

window.__VUE_DEVTOOLS_GLOBAL_HOOK__ = {
  enabled: true,
  emit(event, arg1, uid) {
    if (event === 'app:init') {
      mountedApp = arg1
      // Reset all per-app state
      emitTree('mount')
    } else if (event === 'component:added') {
      emitTree('mount')        // handles dynamic additions after initial mount
    } else if (event === 'component:updated') {
      thisRoundUpdatedUids[String(uid)] = true
      emitTree('update')
    }
  }
}

app:init timing

Vue fires lifecycle events in this order:

  1. component:added — for every component, children before parents
  2. app:init — after the entire tree has mounted

mountedApp is null during all component:added events at initial mount. emitTree from app:init is the first call that has a valid mountedApp.

_cycleUids pattern (selective updateCount)

var thisRoundUpdatedUids = {}   // accumulates UIDs during component:updated calls in current tick
var _cycleUids = {}             // snapshot captured inside the setTimeout callback

function emitTree(type) {
  if (pendingPost || !mountedApp) return
  pendingPost = setTimeout(function() {
    pendingPost = null
    _cycleUids = thisRoundUpdatedUids   // batch all same-tick updates
    thisRoundUpdatedUids = {}
    // build tree — buildComponentTree checks _cycleUids[uid] to decide whether to increment updateCount
    _cycleUids = {}
  }, 0)
}

This ensures that when multiple components update in the same synchronous tick (e.g., both CounterSection and MessageSection), all their UIDs are captured before buildComponentTree runs.

Dep → variable name mapping

flowchart LR
  raw["instance.devtoolsRawSetupState\n(set by Vue __DEV__ build\nonly when setup returns an object)\n{count: RefImpl, doubled: ComputedRefImpl}"]
  raw -->|"Pass 1:\nfor each ref/reactive entry\nif raw.__v_isRef && raw.dep"| map["depToEntry: WeakMap\nDep object → {name: 'count', raw: RefImpl}"]

  eff["component.effect.deps\n(Vue 3.5 linked list)\nlink.dep → link.nextDep → ..."]
  eff -->|"Pass 2:\nfor each Link in linked list\ndepToEntry.has(link.dep) ?"| map

  map -->|"hit"| named["DepNode { name: 'count', type: 'ref' }"]
  map -->|"miss (fallback)"| gen["DepNode { name: 'dep-1', type: 'ref' }"]
Loading

inject('count') returns the same RefImpl object that provide('count', count) registered. The Dep object at RefImpl.dep is the same one that appears in every subscriber's effect.deps linked list. This identity equality is what makes the WeakMap lookup work across component boundaries.

Dep type detection

if (raw.__v_isRef && raw.effect)              → type = 'computed'  // ComputedRefImpl has .effect
if (raw.__v_isReactive && !raw.__v_isRef)     → type = 'reactive'
else                                           → type = 'ref'

postMessage payload

{
  source: 'vue-probe',
  type: 'mount' | 'update',
  timestamp: Date.now(),
  componentId, componentName,
  payload: {
    componentTree: VueComponentNode,   // full tree rooted at App
    reactivityGraph: { nodes, edges }  // dep graph built fresh each emit
  }
}

9. Bridge Layer

useBridge (src/hooks/useBridge.ts)

export function useBridge() {
  // Reset store when framework changes
  useEffect(() => { useBridgeStore.getState().clearAll() }, [framework])

  useEffect(() => {
    function onMessage(e: MessageEvent) {
      const store = useBridgeStore.getState()   // always latest — no closure staleness
      if (isReactEvent(e.data)) {
        const tree = adaptReactEvent(e.data, store.fiberTree)
        if (tree) store.setFiberTree(tree)
        store.pushEvent(e.data)
      }
      if (isVueEvent(e.data)) {
        const { tree, graph } = adaptVueEvent(e.data, store.depGraph)
        if (tree) store.setVueTree(tree)
        if (graph) store.setDepGraph(graph)
        store.pushEvent(e.data)
      }
    }
    window.addEventListener('message', onMessage)
    return () => window.removeEventListener('message', onMessage)
  }, [])  // empty deps — handler uses getState(), not closure state
}

React Adapter (src/adapters/react/index.ts)

The probe always emits renderCount = 0. The adapter owns cumulative counting:

function mergeRenderCount(node: FiberNode, prevById: Map<string, FiberNode>): FiberNode {
  const prev = prevById.get(node.id)
  return {
    ...node,
    renderCount: (prev?.renderCount ?? 0) + (node.didRerender ? 1 : 0),
    children: node.children.map(child => mergeRenderCount(child, prevById)),
  }
}

Nodes where didRerender = false (bailed out) keep their previous renderCount unchanged.

Vue Adapter (src/adapters/vue/index.ts)

Pass-through — the probe builds both the component tree and the reactivity graph fresh on every emit:

export function adaptVueEvent(event, _prevGraph) {
  return {
    tree:  event.payload.componentTree  ?? null,
    graph: event.payload.reactivityGraph ?? null,
  }
}

10. Visualizer: TreeVisualizer (src/components/Visualizer/TreeVisualizer.tsx)

Layout algorithm

Recursive Reingold-Tilford-ish layout. Constants: NODE_W=180, NODE_H=80, H_GAP=24, V_GAP=60.

layoutSubtree(node, depth, xOffset):
  if leaf:
    return [{ x: xOffset, y: depth*(NODE_H+V_GAP), subtreeW: NODE_W }]
  else:
    lay out each child left-to-right with H_GAP between them
    parent.x = center of combined children width
    return [parent, ...all descendants]

AutoFitView

Calls fitView() only when the set of node IDs changes (structural change), not on every data update. Prevents the camera jumping during re-render animations.

FiberNodeCard variants

Variant Used for Visual
InternalNodeCard fiber-root, HostRoot Dashed border, muted
UserComponentCard function, class Solid border, heat color, flash animation
HostElementCard host (div, p, etc.) Thin border, <tag> label
HostTextCard host-text Italic text content

Flash animation: JavaScript adds then removes the .fx-flash CSS class. The CSS @keyframes fx-flash animates a cyan glow pulse (rgba(0, 212, 255, 0.7)).

Heat color scale by renderCount:

Count Color
1 #CBD5E1 (slate)
2-4 #EAB308 (yellow)
5-9 #F97316 (orange)
10+ #EF4444 (red)

11. Visualizer: ReactivityGraph (src/components/Visualizer/ReactivityGraph.tsx)

Layout

Two-column, static positions. Constants: NODE_W=180, NODE_H=64, V_GAP=20, COL_GAP=260.

  • State nodes (ref, computed, reactive): x = 0, stacked vertically
  • Component nodes: x = NODE_W + COL_GAP = 440, stacked vertically
  • Edges flow left to right: state → component

Node color scheme

Type Background Border Dot
ref #EFF6FF #BFDBFE #3B82F6
computed #F5F3FF #DDD6FE #8B5CF6
reactive #F0FDFA #99F6E4 #14B8A6
component heat-based heat-based #10B981

Component node heat (by updateCount): same scale as fiber tree but applied to background and border rather than border alone.

DepNodeCard

Flashes when updateCount changes (component nodes). Uses useRef to track previous count and setTimeout to clear the flash state after 700ms.