{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "text-viewer-chenglou",
  "title": "Chenglou Text Viewer",
  "description": "An imperative Pretext prose viewer that keeps Text Viewer parsing/layout but projects visible rows through a Chenglou-style DOM cache.",
  "registryDependencies": [
    "@retab/text-viewer"
  ],
  "files": [
    {
      "path": "registry/new-york-v4/ui/text-viewer-chenglou.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { PlainTextViewerFrame } from \"./plain-text-viewer-frame\";\nimport { TextViewerContent } from \"./text-viewer-chenglou-content\";\nimport { TextViewerFallback } from \"./text-viewer-chrome\";\nimport type { TextViewerHandle, TextViewerProps } from \"./text-viewer-types\";\n\nexport const ChenglouTextViewer = React.forwardRef<\n  TextViewerHandle,\n  TextViewerProps\n>(function ChenglouTextViewer(props, ref) {\n  return (\n    <PlainTextViewerFrame\n      props={props}\n      forwardedRef={ref}\n      clientFallbackPolicy=\"always\"\n      Fallback={TextViewerFallback}\n      Content={TextViewerContent}\n    />\n  );\n});\n",
      "type": "registry:ui",
      "target": "@ui/text-viewer-chenglou.tsx"
    },
    {
      "path": "registry/new-york-v4/ui/text-viewer-chenglou-content.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { useMountEffect } from \"@/hooks/use-mount-effect\";\n\nimport type { ViewerResource } from \"@/lib/viewer-resource\";\n\nimport { ScrollArea } from \"./scroll-area\";\nimport { TextViewerControls, TextViewerFrame } from \"./text-viewer-chrome\";\nimport {\n  createPreparedTextDocument,\n  getCodeVisibleLineWindow,\n  getInlineVisibleLineWindow,\n  getTableVisibleRowWindow,\n  layoutTextDocument,\n  materializeCodeVisibleLines,\n  materializeInlineVisibleLines,\n  resolveTextViewerMode,\n  serializeMarkdownTableForClipboard,\n  textFrameIntersectsLineRange,\n  type CodeTextBlockFrame,\n  type ImageTextBlockFrame,\n  type InlineTextBlockFrame,\n  type PreparedCodeTextBlock,\n  type PreparedImageTextBlock,\n  type PreparedInlineTextBlock,\n  type PreparedRuleTextBlock,\n  type PreparedTableCell,\n  type PreparedTableTextBlock,\n  type PreparedTextBlock,\n  type RuleTextBlockFrame,\n  type TableTextBlockFrame,\n  type TextBlockFrame,\n  type TextDocumentFrame,\n} from \"./text-viewer-layout\";\nimport { isLineInRange, normalizeTextLineRange } from \"./text-viewer-ranges\";\nimport {\n  readTextDocument,\n  resolvedTextViewerBounds,\n} from \"./text-viewer-resource\";\nimport { clampTextViewerScale } from \"./text-viewer-scale\";\nimport type { TextViewerHandle, TextViewerProps } from \"./text-viewer-types\";\nimport {\n  getTextFrameScrollAnchor,\n  getTextFrameVirtualItems,\n  getTextInverseStickyWindow,\n  type TextFrameScrollAnchor,\n  type TextInverseStickyWindow,\n} from \"./text-viewer-virtualization\";\nimport { useKeyedMountEffect } from \"@/hooks/use-keyed-mount-effect\";\nimport { useKeyedLayoutEffect } from \"@/hooks/use-keyed-layout-effect\";\nimport { joinEffectKey } from \"@/lib/effect-key\";\nimport { patchKeyedDomChildren } from \"./text-viewer-dom-projection\";\nimport { useTextViewerScrollInteractions } from \"./text-viewer-scroll-interactions\";\nimport { resolveFileViewerRendererLayoutInlineSize } from \"./file-viewer-renderer-contract\";\nimport {\n  useOptionalFileViewerRendererEnvironment,\n  useOptionalFileViewerRendererFrame,\n} from \"./file-viewer-renderer-frame\";\n\nconst TEXT_VIEWER_HORIZONTAL_PADDING = 16;\nconst TEXT_VIEWER_DEFAULT_VIEWPORT_HEIGHT = 600;\nconst TEXT_VIEWER_DEFAULT_VIEWPORT_WIDTH = 800;\nconst TEXT_VIEWER_INITIAL_TEXT_WIDTH = 768;\nconst TEXT_VIEWER_OVERSCAN_PX = 800;\nconst TEXT_VIEWER_HIGHLIGHT_BACKGROUND =\n  \"color-mix(in oklab, var(--foreground) 8%, var(--background))\";\nconst TEXT_VIEWER_HIGHLIGHT_ACCENT_SHADOW = \"inset 2px 0 0 0 var(--primary)\";\nconst TEXT_VIEWER_MAX_RECYCLED_ROWS = 512;\nconst TEXT_VIEWER_NATIVE_FIND_CHUNK_SIZE = 128;\n\ntype CachedRow = {\n  renderKey: string;\n  row: HTMLDivElement;\n  visibleWindowKey: string;\n};\n\ntype ProjectionWindow = {\n  after: HTMLDivElement;\n  before: HTMLDivElement;\n  content: HTMLDivElement;\n  sticky: HTMLDivElement;\n};\n\nexport type TextProjectionMetrics = {\n  noops: number;\n  projections: number;\n  rowContentPatches: number;\n  rowLayoutPatches: number;\n  rowPoolSize: number;\n  rowsCreated: number;\n  rowsDropped: number;\n  rowsRemoved: number;\n  rowsReused: number;\n  visibleEnd: number;\n  visibleStart: number;\n};\n\nexport type ProjectionCache = {\n  canvas: HTMLDivElement | null;\n  frame: TextDocumentFrame | null;\n  hasProjection: boolean;\n  metrics?: TextProjectionMetrics;\n  mountedEnd: number;\n  mountedStart: number;\n  preparedDocument: ReturnType<typeof createPreparedTextDocument> | null;\n  projectionWindow: ProjectionWindow | null;\n  recycledRows: CachedRow[];\n  rows: Array<CachedRow | undefined>;\n};\n\ntype ProjectionState = {\n  cache: ProjectionCache;\n  canvas: HTMLDivElement | null;\n  contentWidth: number;\n  frame: TextDocumentFrame;\n  highlightRange: ReturnType<typeof normalizeTextLineRange>;\n  preparedDocument: ReturnType<typeof createPreparedTextDocument>;\n  viewportHeight: number;\n};\n\ntype ViewportSize = {\n  height: number;\n  width: number;\n};\n\ntype NativeFindTextChunk = {\n  endLine: number;\n  startLine: number;\n  text: string;\n};\n\ntype TextIdleWindow = Window &\n  typeof globalThis & {\n    cancelIdleCallback?: Window[\"cancelIdleCallback\"];\n    requestIdleCallback?: Window[\"requestIdleCallback\"];\n  };\n\nexport function createTextProjectionMetrics(): TextProjectionMetrics {\n  return {\n    noops: 0,\n    projections: 0,\n    rowContentPatches: 0,\n    rowLayoutPatches: 0,\n    rowPoolSize: 0,\n    rowsCreated: 0,\n    rowsDropped: 0,\n    rowsRemoved: 0,\n    rowsReused: 0,\n    visibleEnd: 0,\n    visibleStart: 0,\n  };\n}\n\nexport function createTextProjectionCache({\n  metrics,\n}: {\n  metrics?: TextProjectionMetrics;\n} = {}): ProjectionCache {\n  return {\n    canvas: null,\n    frame: null,\n    hasProjection: false,\n    metrics,\n    mountedEnd: 0,\n    mountedStart: 0,\n    preparedDocument: null,\n    projectionWindow: null,\n    recycledRows: [],\n    rows: [],\n  };\n}\n\nexport function TextViewerContent({\n  resource,\n  className,\n  controls = true,\n  download = true,\n  highlight,\n  bare = false,\n  maxBytes,\n  maxLines,\n  retryVersion,\n  forwardedRef,\n  mode: forcedMode,\n  projection = \"chenglou\",\n}: Omit<TextViewerProps, \"source\"> & {\n  resource: ViewerResource;\n  retryVersion: number;\n  forwardedRef?: React.ForwardedRef<TextViewerHandle>;\n  projection?: \"chenglou\" | \"vanillacheng\";\n}) {\n  const bounds = React.useMemo(\n    () => resolvedTextViewerBounds({ maxBytes, maxLines }),\n    [maxBytes, maxLines],\n  );\n  const textDocument = React.useMemo(\n    () =>\n      readTextDocument({\n        bounds,\n        content: resource.content,\n        retryVersion,\n      }),\n    [bounds, resource.content, retryVersion],\n  );\n  const text = textDocument.text;\n  const textLines = textDocument.lines;\n  const mode = React.useMemo(\n    () =>\n      forcedMode ??\n      resolveTextViewerMode({\n        fileName: resource.fileName,\n        mimeType: resource.content.mimeType,\n      }),\n    [forcedMode, resource.content.mimeType, resource.fileName],\n  );\n  const downloadAction = download ? resource.originalDownload : null;\n  const [fontScale, setFontScale] = React.useState(1);\n  const viewportRef = React.useRef<HTMLDivElement | null>(null);\n  const canvasRef = React.useRef<HTMLDivElement | null>(null);\n  const projectionCacheRef = React.useRef<ProjectionCache>(\n    createTextProjectionCache(),\n  );\n  const pendingScrollAnchorRef = React.useRef<TextFrameScrollAnchor | null>(\n    null,\n  );\n  const projectionStateRef = React.useRef<ProjectionState | null>(null);\n  const scheduledRenderRef = React.useRef<number | null>(null);\n  const fontEpoch = useTextViewerFontEpoch();\n  const [contentWidth, setContentWidth] = React.useState(\n    TEXT_VIEWER_INITIAL_TEXT_WIDTH,\n  );\n  const [viewportSize, setViewportSize] = React.useState<ViewportSize>({\n    height: 0,\n    width: 0,\n  });\n  const { usesShellGeometry } = useOptionalFileViewerRendererEnvironment();\n  const rendererFrame = useOptionalFileViewerRendererFrame({\n    fallbackInlineSize: viewportSize.width || null,\n  });\n  const viewportHeight =\n    viewportSize.height || TEXT_VIEWER_DEFAULT_VIEWPORT_HEIGHT;\n  const measuredViewportWidth =\n    viewportSize.width || TEXT_VIEWER_DEFAULT_VIEWPORT_WIDTH;\n  const viewportWidth = usesShellGeometry\n    ? measuredViewportWidth\n    : (resolveFileViewerRendererLayoutInlineSize({\n        fallbackInlineSize: measuredViewportWidth,\n        rendererFrame,\n      }) ?? measuredViewportWidth);\n  const documentInlineSize = contentWidth + TEXT_VIEWER_HORIZONTAL_PADDING * 2;\n\n  const preparedDocument = React.useMemo(\n    () =>\n      createPreparedTextDocument({\n        lines: mode === \"text\" ? textLines : undefined,\n        mode,\n        style: { fontEpoch, fontScale: 1 },\n        text,\n      }),\n    [fontEpoch, mode, text, textLines],\n  );\n  const frame = React.useMemo(\n    () =>\n      layoutTextDocument({\n        contentWidth,\n        document: preparedDocument,\n        fontScale,\n      }),\n    [contentWidth, fontScale, preparedDocument],\n  );\n  const highlightStart = highlight?.start;\n  const highlightEnd = highlight?.end;\n  const highlightRange = React.useMemo(\n    () =>\n      normalizeTextLineRange(\n        highlightStart == null || highlightEnd == null\n          ? null\n          : { end: highlightEnd, start: highlightStart },\n        preparedDocument.sourceLineCount,\n      ),\n    [highlightEnd, highlightStart, preparedDocument.sourceLineCount],\n  );\n\n  const captureScrollAnchor = React.useCallback(() => {\n    pendingScrollAnchorRef.current = getTextFrameScrollAnchor({\n      frames: frame.frames,\n      scrollTop: viewportRef.current?.scrollTop ?? 0,\n    });\n  }, [frame.frames]);\n\n  const projectCurrentRows = React.useCallback(() => {\n    const state = projectionStateRef.current;\n    if (!state) return;\n\n    const scrollElement = viewportRef.current;\n\n    projectRows({\n      cache: state.cache,\n      canvas: state.canvas,\n      contentWidth: state.contentWidth,\n      frame: state.frame,\n      highlightRange: state.highlightRange,\n      preparedDocument: state.preparedDocument,\n      scrollTop: scrollElement?.scrollTop ?? 0,\n      viewportHeight: scrollElement?.clientHeight || state.viewportHeight,\n    });\n  }, []);\n\n  const scheduleProjectRows = React.useCallback(() => {\n    if (scheduledRenderRef.current !== null) return;\n    scheduledRenderRef.current = requestAnimationFrame(\n      function renderChenglouTextFrame() {\n        scheduledRenderRef.current = null;\n        projectCurrentRows();\n      },\n    );\n  }, [projectCurrentRows]);\n  const getScrollInteractionTarget = React.useCallback(\n    () =>\n      projectionCacheRef.current.projectionWindow?.sticky ?? canvasRef.current,\n    [],\n  );\n  const getScrollOverflowTarget = React.useCallback(\n    () =>\n      projectionCacheRef.current.projectionWindow?.sticky ?? canvasRef.current,\n    [],\n  );\n\n  useKeyedLayoutEffect(\n    joinEffectKey([\"viewport-resize\", usesShellGeometry]),\n    () => {\n      const scrollElement = viewportRef.current;\n      if (!scrollElement) return;\n\n      const readViewportSize = () => {\n        const nextHeight = scrollElement.clientHeight;\n        setViewportSize((current) => {\n          const nextWidth =\n            usesShellGeometry && current.width > 0\n              ? current.width\n              : scrollElement.clientWidth;\n\n          return current.width === nextWidth && current.height === nextHeight\n            ? current\n            : { height: nextHeight, width: nextWidth };\n        });\n      };\n\n      readViewportSize();\n      const resizeObserver =\n        typeof ResizeObserver === \"undefined\"\n          ? null\n          : new ResizeObserver(readViewportSize);\n      resizeObserver?.observe(scrollElement);\n\n      return () => {\n        resizeObserver?.disconnect();\n      };\n    },\n  );\n\n  useTextViewerScrollInteractions({\n    getInteractionTarget: getScrollInteractionTarget,\n    getOverflowTarget: getScrollOverflowTarget,\n    onScroll: scheduleProjectRows,\n    viewportRef,\n  });\n\n  useKeyedLayoutEffect(\n    joinEffectKey([\n      captureScrollAnchor,\n      rendererFrame.documentTransition.layoutPolicy,\n      rendererFrame.documentTransition.transitionId,\n      viewportWidth,\n    ]),\n    () => {\n      const nextContentWidth = Math.max(\n        1,\n        viewportWidth - TEXT_VIEWER_HORIZONTAL_PADDING * 2,\n      );\n      setContentWidth((current) => {\n        if (current === nextContentWidth) return current;\n        captureScrollAnchor();\n        return nextContentWidth;\n      });\n    },\n  );\n\n  useKeyedLayoutEffect(joinEffectKey([frame.frames]), () => {\n    const anchor = pendingScrollAnchorRef.current;\n    const scrollElement = viewportRef.current;\n    if (!anchor || !scrollElement) return;\n\n    pendingScrollAnchorRef.current = null;\n    const nextFrame = frame.frames[anchor.index];\n    if (!nextFrame) return;\n\n    scrollElement.scrollTop = Math.max(\n      0,\n      nextFrame.top +\n        Math.min(anchor.offsetWithinFrame, Math.max(0, nextFrame.height - 1)),\n    );\n  });\n\n  useKeyedLayoutEffect(\n    joinEffectKey([\n      contentWidth,\n      frame,\n      highlightRange,\n      projectCurrentRows,\n      preparedDocument,\n      viewportHeight,\n    ]),\n    () => {\n      projectionStateRef.current = {\n        cache: projectionCacheRef.current,\n        canvas: canvasRef.current,\n        contentWidth,\n        frame,\n        highlightRange,\n        preparedDocument,\n        viewportHeight,\n      };\n      projectCurrentRows();\n    },\n  );\n\n  useMountEffect(() => () => {\n    if (scheduledRenderRef.current !== null) {\n      cancelAnimationFrame(scheduledRenderRef.current);\n    }\n  });\n\n  const scrollLineRange = React.useCallback(\n    (\n      range: ReturnType<typeof normalizeTextLineRange>,\n      options?: ScrollToOptions,\n    ) => {\n      const scrollElement = viewportRef.current;\n      if (!scrollElement || !range) return;\n\n      const targetFrame =\n        frame.frames.find((item) =>\n          textFrameIntersectsLineRange({ frame: item, range }),\n        ) ?? frame.frames[0];\n      if (!targetFrame) return;\n\n      const targetTop =\n        targetFrame.height <= scrollElement.clientHeight\n          ? targetFrame.top -\n            (scrollElement.clientHeight - targetFrame.height) / 2\n          : targetFrame.top;\n\n      scrollElement.scrollTo({\n        behavior: \"smooth\",\n        top: Math.max(0, targetTop),\n        ...options,\n      });\n    },\n    [frame.frames],\n  );\n\n  const zoom = (factor: number) => {\n    captureScrollAnchor();\n    setFontScale((scale) => clampTextViewerScale(scale * factor));\n  };\n\n  const resetZoom = () => {\n    captureScrollAnchor();\n    setFontScale(1);\n  };\n\n  React.useImperativeHandle(\n    forwardedRef ?? null,\n    () => ({\n      getViewportElement: () => viewportRef.current,\n      scrollToLineRange: (range, options) => {\n        scrollLineRange(\n          normalizeTextLineRange(range, preparedDocument.sourceLineCount),\n          options,\n        );\n      },\n    }),\n    [preparedDocument.sourceLineCount, scrollLineRange],\n  );\n\n  useKeyedMountEffect(joinEffectKey([highlightRange, scrollLineRange]), () => {\n    scrollLineRange(highlightRange, { behavior: \"auto\" });\n  });\n\n  const scrollMarkdownFragment = React.useCallback(\n    (event: React.MouseEvent) => {\n      const href = localFragmentHrefFromEventTarget(event.target);\n      if (!href) return;\n\n      const targetId = decodeMarkdownFragmentHref(href);\n      const targetIndex = markdownHeadingBlockIndex(\n        preparedDocument.blocks,\n        targetId,\n      );\n      const targetFrame = frame.frames[targetIndex];\n      const scrollElement = viewportRef.current;\n      if (!targetFrame || !scrollElement) return;\n\n      event.preventDefault();\n      scrollElement.scrollTo({\n        behavior: \"smooth\",\n        top: Math.max(0, targetFrame.top),\n      });\n      if (window.location.hash !== href) {\n        window.history.replaceState(null, \"\", href);\n      }\n    },\n    [frame.frames, preparedDocument.blocks],\n  );\n\n  return (\n    <TextViewerFrame className={className} bare={bare}>\n      {controls ? (\n        <TextViewerControls\n          wordCount={preparedDocument.wordCount}\n          fontScale={fontScale}\n          downloadAction={downloadAction}\n          onZoomOut={() => zoom(1 / 1.2)}\n          onZoomIn={() => zoom(1.2)}\n          onResetZoom={resetZoom}\n        />\n      ) : null}\n      <ScrollArea\n        className=\"bg-background min-h-0 flex-1\"\n        orientation=\"vertical\"\n        viewportClassName=\"bg-background [overflow-anchor:none]\"\n        viewportProps={{ onClickCapture: scrollMarkdownFragment }}\n        viewportRef={viewportRef}\n      >\n        <div\n          className=\"relative min-w-0\"\n          style={{ minWidth: documentInlineSize }}\n        >\n          {mode === \"text\" ? (\n            <DeferredNativeFindIndex\n              lineCount={preparedDocument.sourceLineCount}\n              lines={textLines}\n              scrollToLineRange={scrollLineRange}\n            />\n          ) : null}\n          <div\n            ref={canvasRef}\n            className=\"relative min-w-0\"\n            data-slot=\"text-virtual-canvas\"\n            data-projection={projection}\n            style={{\n              height: frame.totalHeight,\n              minWidth: documentInlineSize,\n            }}\n          />\n        </div>\n      </ScrollArea>\n    </TextViewerFrame>\n  );\n}\n\nfunction DeferredNativeFindIndex({\n  lines,\n  lineCount,\n  scrollToLineRange,\n}: {\n  lines: readonly string[];\n  lineCount: number;\n  scrollToLineRange: (\n    range: ReturnType<typeof normalizeTextLineRange>,\n    options?: ScrollToOptions,\n  ) => void;\n}) {\n  const [isReady, setIsReady] = React.useState(false);\n\n  useKeyedMountEffect(joinEffectKey([lines]), () => {\n    setIsReady(false);\n    const show = () => setIsReady(true);\n    if (typeof window === \"undefined\") return;\n    const browserWindow = window as TextIdleWindow;\n    if (browserWindow.requestIdleCallback && browserWindow.cancelIdleCallback) {\n      const idleId = browserWindow.requestIdleCallback(show, { timeout: 400 });\n      return () => browserWindow.cancelIdleCallback?.(idleId);\n    }\n    const timeoutId = browserWindow.setTimeout(show, 80);\n    return () => browserWindow.clearTimeout(timeoutId);\n  });\n\n  if (!isReady) return null;\n  return (\n    <NativeFindIndex\n      lineCount={lineCount}\n      lines={lines}\n      scrollToLineRange={scrollToLineRange}\n    />\n  );\n}\n\nfunction NativeFindIndex({\n  lines,\n  lineCount,\n  scrollToLineRange,\n}: {\n  lines: readonly string[];\n  lineCount: number;\n  scrollToLineRange: (\n    range: ReturnType<typeof normalizeTextLineRange>,\n    options?: ScrollToOptions,\n  ) => void;\n}) {\n  const entries = React.useMemo(() => chunkNativeFindLines(lines), [lines]);\n\n  return (\n    <div\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute top-0 left-0 h-px w-px overflow-hidden opacity-0\"\n      data-native-find-indexed-chunks={entries.length}\n      data-native-find-indexed-lines={lines.length}\n      data-slot=\"text-native-find-index\"\n    >\n      {entries.map((entry) => (\n        <NativeFindEntry\n          key={entry.startLine}\n          entry={entry}\n          lineCount={lineCount}\n          scrollToLineRange={scrollToLineRange}\n        />\n      ))}\n    </div>\n  );\n}\n\nfunction NativeFindEntry({\n  entry,\n  lineCount,\n  scrollToLineRange,\n}: {\n  entry: NativeFindTextChunk;\n  lineCount: number;\n  scrollToLineRange: (\n    range: ReturnType<typeof normalizeTextLineRange>,\n    options?: ScrollToOptions,\n  ) => void;\n}) {\n  const ref = React.useRef<HTMLSpanElement | null>(null);\n\n  useKeyedLayoutEffect(\n    joinEffectKey([\n      entry.startLine,\n      entry.endLine,\n      lineCount,\n      scrollToLineRange,\n    ]),\n    () => {\n      const element = ref.current;\n      if (!element) return;\n      element.setAttribute(\"hidden\", \"until-found\");\n\n      const handleBeforeMatch = () => {\n        scrollToLineRange(\n          normalizeTextLineRange(\n            {\n              end: entry.endLine,\n              start: entry.startLine,\n            },\n            lineCount,\n          ),\n          { behavior: \"auto\" },\n        );\n        requestAnimationFrame(() => {\n          element.setAttribute(\"hidden\", \"until-found\");\n        });\n      };\n\n      element.addEventListener(\"beforematch\", handleBeforeMatch);\n      return () => {\n        element.removeEventListener(\"beforematch\", handleBeforeMatch);\n      };\n    },\n  );\n\n  return (\n    <span\n      ref={ref}\n      className=\"absolute top-0 left-0 block h-px w-px overflow-hidden whitespace-pre\"\n      data-native-find-end-line={entry.endLine}\n      data-native-find-start-line={entry.startLine}\n    >\n      {entry.text || \" \"}\n    </span>\n  );\n}\n\nfunction chunkNativeFindLines(lines: readonly string[]): NativeFindTextChunk[] {\n  const chunks: NativeFindTextChunk[] = [];\n  for (\n    let startIndex = 0;\n    startIndex < lines.length;\n    startIndex += TEXT_VIEWER_NATIVE_FIND_CHUNK_SIZE\n  ) {\n    const endIndex = Math.min(\n      lines.length,\n      startIndex + TEXT_VIEWER_NATIVE_FIND_CHUNK_SIZE,\n    );\n    chunks.push({\n      endLine: endIndex,\n      startLine: startIndex + 1,\n      text: lines.slice(startIndex, endIndex).join(\"\\n\"),\n    });\n  }\n  return chunks;\n}\n\nexport function projectRows({\n  cache,\n  canvas,\n  contentWidth,\n  frame,\n  highlightRange,\n  preparedDocument,\n  scrollTop,\n  viewportHeight,\n}: {\n  cache: ProjectionCache;\n  canvas: HTMLDivElement | null;\n  contentWidth: number;\n  frame: TextDocumentFrame;\n  highlightRange: ReturnType<typeof normalizeTextLineRange>;\n  preparedDocument: ReturnType<typeof createPreparedTextDocument>;\n  scrollTop: number;\n  viewportHeight: number;\n}) {\n  incrementTextMetric(cache.metrics, \"projections\");\n  if (!canvas) return;\n\n  if (cache.canvas !== canvas) {\n    clearCachedRows(cache, cache.canvas);\n    cache.canvas = canvas;\n  }\n\n  if (cache.frame !== frame || cache.preparedDocument !== preparedDocument) {\n    clearCachedRows(cache, canvas);\n    cache.frame = frame;\n    cache.preparedDocument = preparedDocument;\n  }\n\n  const totalHeight = `${frame.totalHeight}px`;\n  setStyleValue(canvas.style, \"height\", totalHeight);\n  const virtualItems = getTextFrameVirtualItems({\n    frames: frame.frames,\n    overscanPx: TEXT_VIEWER_OVERSCAN_PX,\n    scrollTop,\n    viewportHeight,\n  });\n  const start = virtualItems[0]?.index ?? 0;\n  const end = virtualItems.length\n    ? virtualItems[virtualItems.length - 1]!.index + 1\n    : start;\n  setTextMetric(cache.metrics, \"visibleStart\", start);\n  setTextMetric(cache.metrics, \"visibleEnd\", end);\n  const previousStart = cache.mountedStart;\n  const previousEnd = cache.mountedEnd;\n  const overlapStart = Math.max(start, previousStart);\n  const overlapEnd = Math.min(end, previousEnd);\n  const viewportTop = scrollTop - TEXT_VIEWER_OVERSCAN_PX;\n  const viewportBottom = scrollTop + viewportHeight + TEXT_VIEWER_OVERSCAN_PX;\n  const stickyWindow = getTextInverseStickyWindow({\n    renderedBottom: virtualItems.at(-1)?.end ?? 0,\n    renderedTop:\n      virtualItems[0]?.index === 0 ? 0 : (virtualItems[0]?.start ?? 0),\n    totalHeight: frame.totalHeight,\n    viewportHeight,\n  });\n  const projectionWindow = ensureProjectionWindow(cache, canvas);\n  syncProjectionWindow(projectionWindow, stickyWindow);\n\n  const project = (index: number) => {\n    const block = preparedDocument.blocks[index];\n    const blockFrame = frame.frames[index];\n    if (!block || !blockFrame) return null;\n    const cachedRow = prepareRow({\n      block,\n      cache,\n      contentWidth,\n      frame: blockFrame,\n      highlightRange,\n      index,\n      renderedTop: stickyWindow.renderedTop,\n      viewportBottom,\n      viewportTop,\n    });\n    projectRowNode(\n      cachedRow.row,\n      blockFrame,\n      stickyWindow.renderedTop,\n      cache.metrics,\n    );\n    return cachedRow.row;\n  };\n\n  if (\n    cache.hasProjection &&\n    previousStart === start &&\n    previousEnd === end &&\n    isRenderedDomValid(cache, projectionWindow.content, start, end)\n  ) {\n    if (\n      areCachedRowsUnchanged({\n        cache,\n        contentWidth,\n        frame,\n        highlightRange,\n        preparedDocument,\n        renderedTop: stickyWindow.renderedTop,\n        start,\n        end,\n        viewportBottom,\n        viewportTop,\n      })\n    ) {\n      incrementTextMetric(cache.metrics, \"noops\");\n      return;\n    }\n\n    for (let index = start; index < end; index++) {\n      project(index);\n    }\n    cache.hasProjection = true;\n    cache.mountedStart = start;\n    cache.mountedEnd = end;\n    return;\n  }\n\n  for (\n    let index = previousStart;\n    index < Math.min(previousEnd, start);\n    index++\n  ) {\n    removeCachedRow(cache, index);\n  }\n  for (let index = Math.max(previousStart, end); index < previousEnd; index++) {\n    removeCachedRow(cache, index);\n  }\n\n  if (overlapStart >= overlapEnd) {\n    for (let index = start; index < end; index++) {\n      const row = project(index);\n      if (row && row.parentNode === null) projectionWindow.content.append(row);\n    }\n  } else {\n    let anchorRow = cache.rows[overlapStart]?.row ?? null;\n    for (let index = overlapStart - 1; index >= start; index--) {\n      const row = project(index);\n      if (!row) continue;\n      if (anchorRow === null) {\n        if (row.parentNode === null) projectionWindow.content.append(row);\n      } else if (\n        row.parentNode !== projectionWindow.content ||\n        row.nextSibling !== anchorRow\n      ) {\n        projectionWindow.content.insertBefore(row, anchorRow);\n      }\n      anchorRow = row;\n    }\n\n    for (let index = overlapStart; index < overlapEnd; index++) {\n      project(index);\n    }\n\n    for (let index = overlapEnd; index < end; index++) {\n      const row = project(index);\n      if (row && row.parentNode === null) projectionWindow.content.append(row);\n    }\n  }\n\n  cache.mountedStart = start;\n  cache.mountedEnd = end;\n  cache.hasProjection = true;\n}\n\nfunction removeCachedRow(cache: ProjectionCache, index: number) {\n  const cachedRow = cache.rows[index];\n  if (!cachedRow) return;\n  cachedRow.row.remove();\n  incrementTextMetric(cache.metrics, \"rowsRemoved\");\n  recycleCachedRow(cache, cachedRow);\n  cache.rows[index] = undefined;\n}\n\nfunction clearCachedRows(\n  cache: ProjectionCache,\n  canvas: HTMLDivElement | null,\n) {\n  for (const cachedRow of cache.rows) {\n    if (!cachedRow) continue;\n    cachedRow.row.remove();\n    incrementTextMetric(cache.metrics, \"rowsRemoved\");\n    recycleCachedRow(cache, cachedRow);\n  }\n  canvas?.replaceChildren();\n  cache.hasProjection = false;\n  cache.mountedEnd = 0;\n  cache.mountedStart = 0;\n  cache.projectionWindow = null;\n  cache.rows = [];\n}\n\nfunction ensureProjectionWindow(\n  cache: ProjectionCache,\n  canvas: HTMLDivElement,\n): ProjectionWindow {\n  const existing = cache.projectionWindow;\n  if (existing?.before.parentElement === canvas) return existing;\n\n  const before = document.createElement(\"div\");\n  const sticky = document.createElement(\"div\");\n  const content = document.createElement(\"div\");\n  const after = document.createElement(\"div\");\n\n  before.dataset.slot = \"text-sticky-before-buffer\";\n  sticky.dataset.slot = \"text-sticky-window\";\n  content.dataset.slot = \"text-sticky-content\";\n  after.dataset.slot = \"text-sticky-after-buffer\";\n\n  before.style.contain = \"layout size\";\n  sticky.style.position = \"sticky\";\n  sticky.style.left = \"0\";\n  sticky.style.width = \"100%\";\n  sticky.style.overflow = \"visible\";\n  sticky.style.contain = \"layout style inline-size\";\n  sticky.style.isolation = \"isolate\";\n  sticky.style.display = \"flex\";\n  sticky.style.flexDirection = \"column\";\n  content.style.position = \"relative\";\n  content.style.width = \"100%\";\n  after.style.contain = \"layout size\";\n\n  sticky.append(content);\n  canvas.replaceChildren(before, sticky, after);\n\n  cache.projectionWindow = {\n    after,\n    before,\n    content,\n    sticky,\n  };\n  return cache.projectionWindow;\n}\n\nfunction syncProjectionWindow(\n  projectionWindow: ProjectionWindow,\n  stickyWindow: TextInverseStickyWindow,\n) {\n  setStyleValue(\n    projectionWindow.before.style,\n    \"height\",\n    `${stickyWindow.beforeHeight}px`,\n  );\n  setStyleValue(\n    projectionWindow.sticky.style,\n    \"top\",\n    `${stickyWindow.stickyOffset}px`,\n  );\n  setStyleValue(\n    projectionWindow.sticky.style,\n    \"bottom\",\n    `${stickyWindow.stickyOffset}px`,\n  );\n  setStyleValue(\n    projectionWindow.sticky.style,\n    \"height\",\n    `${stickyWindow.renderedHeight}px`,\n  );\n  setStyleValue(\n    projectionWindow.content.style,\n    \"height\",\n    `${stickyWindow.renderedHeight}px`,\n  );\n  setStyleValue(\n    projectionWindow.after.style,\n    \"height\",\n    `${stickyWindow.afterHeight}px`,\n  );\n}\n\nfunction prepareRow({\n  block,\n  cache,\n  contentWidth,\n  frame,\n  highlightRange,\n  index,\n  renderedTop,\n  viewportBottom,\n  viewportTop,\n}: {\n  block: PreparedTextBlock;\n  cache: ProjectionCache;\n  contentWidth: number;\n  frame: TextBlockFrame;\n  highlightRange: ReturnType<typeof normalizeTextLineRange>;\n  index: number;\n  renderedTop: number;\n  viewportBottom: number;\n  viewportTop: number;\n}): CachedRow {\n  let cachedRow = cache.rows[index];\n  if (!cachedRow) {\n    cachedRow = acquireCachedRow(cache);\n    cache.rows[index] = cachedRow;\n  }\n\n  const renderKey = rowRenderKey({\n    block,\n    contentWidth,\n    frame,\n    highlightRange,\n  });\n  const visibleWindowKey = blockVisibleWindowKey(\n    frame,\n    viewportTop,\n    viewportBottom,\n  );\n  if (cachedRow.renderKey !== renderKey) {\n    cachedRow.renderKey = renderKey;\n    cachedRow.visibleWindowKey = visibleWindowKey;\n    incrementTextMetric(cache.metrics, \"rowContentPatches\");\n    renderRowContent({\n      block,\n      contentWidth,\n      frame,\n      highlightRange,\n      renderedTop,\n      row: cachedRow.row,\n      viewportBottom,\n      viewportTop,\n    });\n  } else if (cachedRow.visibleWindowKey !== visibleWindowKey) {\n    cachedRow.visibleWindowKey = visibleWindowKey;\n    incrementTextMetric(cache.metrics, \"rowContentPatches\");\n    patchRowContent({\n      block,\n      contentWidth,\n      frame,\n      row: cachedRow.row,\n      viewportBottom,\n      viewportTop,\n    });\n  }\n  return cachedRow;\n}\n\nfunction acquireCachedRow(cache: ProjectionCache): CachedRow {\n  const cachedRow = cache.recycledRows.pop();\n  if (cachedRow) {\n    incrementTextMetric(cache.metrics, \"rowsReused\");\n    setTextMetric(cache.metrics, \"rowPoolSize\", cache.recycledRows.length);\n    return cachedRow;\n  }\n\n  incrementTextMetric(cache.metrics, \"rowsCreated\");\n  return {\n    renderKey: \"\",\n    row: document.createElement(\"div\"),\n    visibleWindowKey: \"\",\n  };\n}\n\nfunction recycleCachedRow(cache: ProjectionCache, cachedRow: CachedRow) {\n  cachedRow.renderKey = \"\";\n  cachedRow.visibleWindowKey = \"\";\n  cachedRow.row.replaceChildren();\n\n  if (cache.recycledRows.length >= TEXT_VIEWER_MAX_RECYCLED_ROWS) {\n    incrementTextMetric(cache.metrics, \"rowsDropped\");\n    setTextMetric(cache.metrics, \"rowPoolSize\", cache.recycledRows.length);\n    return;\n  }\n\n  cache.recycledRows.push(cachedRow);\n  setTextMetric(cache.metrics, \"rowPoolSize\", cache.recycledRows.length);\n}\n\nfunction projectRowNode(\n  row: HTMLDivElement,\n  frame: TextBlockFrame,\n  renderedTop: number,\n  metrics: TextProjectionMetrics | undefined,\n) {\n  let didPatch = false;\n  didPatch =\n    setStyleValue(row.style, \"height\", `${frame.height}px`) || didPatch;\n  didPatch =\n    setStyleValue(\n      row.style,\n      \"transform\",\n      `translateY(${frame.top - renderedTop}px)`,\n    ) || didPatch;\n  if (didPatch) {\n    incrementTextMetric(metrics, \"rowLayoutPatches\");\n  }\n}\n\nfunction areCachedRowsUnchanged({\n  cache,\n  contentWidth,\n  frame,\n  highlightRange,\n  preparedDocument,\n  renderedTop,\n  start,\n  end,\n  viewportBottom,\n  viewportTop,\n}: {\n  cache: ProjectionCache;\n  contentWidth: number;\n  frame: TextDocumentFrame;\n  highlightRange: ReturnType<typeof normalizeTextLineRange>;\n  preparedDocument: ReturnType<typeof createPreparedTextDocument>;\n  renderedTop: number;\n  start: number;\n  end: number;\n  viewportBottom: number;\n  viewportTop: number;\n}) {\n  for (let index = start; index < end; index++) {\n    const block = preparedDocument.blocks[index];\n    const blockFrame = frame.frames[index];\n    const cachedRow = cache.rows[index];\n    if (!block || !blockFrame || !cachedRow) return false;\n    if (!isRowLayoutValid(cachedRow.row, blockFrame, renderedTop)) {\n      return false;\n    }\n    if (\n      cachedRow.renderKey !==\n      rowRenderKey({\n        block,\n        contentWidth,\n        frame: blockFrame,\n        highlightRange,\n      })\n    ) {\n      return false;\n    }\n    if (\n      cachedRow.visibleWindowKey !==\n      blockVisibleWindowKey(blockFrame, viewportTop, viewportBottom)\n    ) {\n      return false;\n    }\n  }\n  return true;\n}\n\nfunction isRenderedDomValid(\n  cache: ProjectionCache,\n  canvas: HTMLDivElement,\n  start: number,\n  end: number,\n) {\n  const expectedLength = Math.max(0, end - start);\n  if (canvas.children.length !== expectedLength) return false;\n\n  for (let offset = 0; offset < expectedLength; offset++) {\n    const index = start + offset;\n    const element = canvas.children[offset];\n    const cachedRow = cache.rows[index];\n    if (!(element instanceof HTMLDivElement) || cachedRow?.row !== element) {\n      return false;\n    }\n  }\n  return true;\n}\n\nfunction isRowLayoutValid(\n  row: HTMLDivElement,\n  frame: TextBlockFrame,\n  renderedTop: number,\n) {\n  return (\n    row.style.height === `${frame.height}px` &&\n    row.style.transform === `translateY(${frame.top - renderedTop}px)`\n  );\n}\n\nfunction setStyleValue(\n  style: CSSStyleDeclaration,\n  propertyName: string,\n  value: string,\n) {\n  if (style.getPropertyValue(propertyName) === value) return false;\n  style.setProperty(propertyName, value);\n  return true;\n}\n\nfunction incrementTextMetric(\n  metrics: TextProjectionMetrics | undefined,\n  key:\n    | \"noops\"\n    | \"projections\"\n    | \"rowContentPatches\"\n    | \"rowLayoutPatches\"\n    | \"rowsCreated\"\n    | \"rowsDropped\"\n    | \"rowsRemoved\"\n    | \"rowsReused\",\n) {\n  if (!metrics) return;\n  metrics[key] += 1;\n}\n\nfunction setTextMetric(\n  metrics: TextProjectionMetrics | undefined,\n  key: \"rowPoolSize\" | \"visibleEnd\" | \"visibleStart\",\n  value: number,\n) {\n  if (!metrics) return;\n  metrics[key] = value;\n}\n\nfunction rowRenderKey({\n  block,\n  contentWidth,\n  frame,\n  highlightRange,\n}: {\n  block: PreparedTextBlock;\n  contentWidth: number;\n  frame: TextBlockFrame;\n  highlightRange: ReturnType<typeof normalizeTextLineRange>;\n}) {\n  return [\n    block.kind,\n    contentWidth,\n    frame.height,\n    frame.top,\n    frame.scale,\n    textFrameIsHighlighted(frame, highlightRange) ? \"highlighted\" : \"\",\n  ].join(\":\");\n}\n\nfunction renderRowContent({\n  block,\n  contentWidth,\n  frame,\n  highlightRange,\n  renderedTop,\n  row,\n  viewportBottom,\n  viewportTop,\n}: {\n  block: PreparedTextBlock;\n  contentWidth: number;\n  frame: TextBlockFrame;\n  highlightRange: ReturnType<typeof normalizeTextLineRange>;\n  renderedTop: number;\n  row: HTMLDivElement;\n  viewportBottom: number;\n  viewportTop: number;\n}) {\n  const isHighlighted = textFrameIsHighlighted(frame, highlightRange);\n  row.replaceChildren();\n  row.className = \"absolute left-0 w-full px-4\";\n  row.dataset.slot = \"text-line\";\n  row.dataset.sourceLine = String(frame.sourceStartLine);\n  if (isHighlighted) {\n    row.dataset.textHighlighted = \"\";\n  } else {\n    delete row.dataset.textHighlighted;\n  }\n  if (block.kind === \"inline\" && block.headingId) {\n    row.id = block.headingId;\n    row.dataset.headingId = block.headingId;\n  } else {\n    row.removeAttribute(\"id\");\n    delete row.dataset.headingId;\n  }\n  if (frame.listDepth) {\n    row.dataset.listDepth = String(frame.listDepth);\n  } else {\n    delete row.dataset.listDepth;\n  }\n  if (frame.quoteDepth) {\n    row.dataset.quoteDepth = String(frame.quoteDepth);\n  } else {\n    delete row.dataset.quoteDepth;\n  }\n  applyRowSemantics(row, block, frame);\n  row.style.position = \"absolute\";\n  row.style.left = \"0\";\n  row.style.width = \"100%\";\n  row.style.paddingLeft = \"16px\";\n  row.style.paddingRight = \"16px\";\n  row.style.height = `${frame.height}px`;\n  row.style.transform = `translateY(${frame.top - renderedTop}px)`;\n  row.style.backgroundColor = isHighlighted\n    ? TEXT_VIEWER_HIGHLIGHT_BACKGROUND\n    : \"\";\n  row.style.boxShadow = isHighlighted\n    ? TEXT_VIEWER_HIGHLIGHT_ACCENT_SHADOW\n    : \"\";\n\n  appendBlockChrome(row, frame);\n\n  switch (block.kind) {\n    case \"inline\":\n      renderInlineBlock({\n        block,\n        contentWidth,\n        frame: frame as InlineTextBlockFrame,\n        row,\n        viewportBottom,\n        viewportTop,\n      });\n      break;\n    case \"code\":\n      renderCodeBlock({\n        block,\n        contentWidth,\n        frame: frame as CodeTextBlockFrame,\n        row,\n        viewportBottom,\n        viewportTop,\n      });\n      break;\n    case \"image\":\n      renderImageBlock({\n        block,\n        frame: frame as ImageTextBlockFrame,\n        row,\n      });\n      break;\n    case \"rule\":\n      renderRuleBlock({\n        frame: frame as RuleTextBlockFrame,\n        row,\n      });\n      break;\n    case \"table\":\n      renderTableBlock({\n        block,\n        frame: frame as TableTextBlockFrame,\n        row,\n        viewportBottom,\n        viewportTop,\n      });\n      break;\n  }\n}\n\nfunction patchRowContent({\n  block,\n  contentWidth,\n  frame,\n  row,\n  viewportBottom,\n  viewportTop,\n}: {\n  block: PreparedTextBlock;\n  contentWidth: number;\n  frame: TextBlockFrame;\n  row: HTMLDivElement;\n  viewportBottom: number;\n  viewportTop: number;\n}) {\n  switch (block.kind) {\n    case \"inline\": {\n      const linesNode = row.querySelector<HTMLElement>(\n        '[data-slot=\"text-inline-lines\"]',\n      );\n      if (!linesNode) return;\n      patchInlineBlockLines({\n        block,\n        contentWidth,\n        frame: frame as InlineTextBlockFrame,\n        linesNode,\n        viewportBottom,\n        viewportTop,\n      });\n      break;\n    }\n    case \"code\": {\n      const code = row.querySelector<HTMLElement>(\n        '[data-slot=\"text-code-lines\"]',\n      );\n      if (!code) return;\n      patchCodeBlockLines({\n        block,\n        code,\n        contentWidth,\n        frame: frame as CodeTextBlockFrame,\n        viewportBottom,\n        viewportTop,\n      });\n      break;\n    }\n    case \"table\": {\n      const tbody = row.querySelector<HTMLTableSectionElement>(\n        '[data-slot=\"text-table-body\"]',\n      );\n      if (!tbody) return;\n      patchTableBodyRows({\n        block,\n        frame: frame as TableTextBlockFrame,\n        tbody,\n        viewportBottom,\n        viewportTop,\n      });\n      break;\n    }\n    case \"image\":\n    case \"rule\":\n      break;\n  }\n}\n\nfunction applyRowSemantics(\n  row: HTMLDivElement,\n  block: PreparedTextBlock,\n  frame: TextBlockFrame,\n) {\n  row.removeAttribute(\"role\");\n  row.removeAttribute(\"aria-level\");\n\n  if (block.kind === \"inline\") {\n    const headingLevel = inlineHeadingLevel(block);\n    if (headingLevel != null) {\n      row.setAttribute(\"role\", \"heading\");\n      row.setAttribute(\"aria-level\", String(headingLevel));\n      return;\n    }\n  }\n\n  if (frame.markerText) {\n    row.setAttribute(\"role\", \"listitem\");\n    row.setAttribute(\"aria-level\", String(frame.listDepth));\n  }\n}\n\nfunction inlineHeadingLevel(block: PreparedInlineTextBlock) {\n  if (block.variant === \"heading-1\") return 1;\n  if (block.variant === \"heading-2\") return 2;\n  return null;\n}\n\nfunction renderInlineBlock({\n  block,\n  contentWidth,\n  frame,\n  row,\n  viewportBottom,\n  viewportTop,\n}: {\n  block: PreparedInlineTextBlock;\n  contentWidth: number;\n  frame: InlineTextBlockFrame;\n  row: HTMLDivElement;\n  viewportBottom: number;\n  viewportTop: number;\n}) {\n  const linesNode = document.createElement(\"div\");\n  linesNode.dataset.slot = \"text-inline-lines\";\n  row.append(linesNode);\n  patchInlineBlockLines({\n    block,\n    contentWidth,\n    frame,\n    linesNode,\n    viewportBottom,\n    viewportTop,\n  });\n}\n\nfunction patchInlineBlockLines({\n  block,\n  contentWidth,\n  frame,\n  linesNode,\n  viewportBottom,\n  viewportTop,\n}: {\n  block: PreparedInlineTextBlock;\n  contentWidth: number;\n  frame: InlineTextBlockFrame;\n  linesNode: HTMLElement;\n  viewportBottom: number;\n  viewportTop: number;\n}) {\n  const lineWindow = getInlineVisibleLineWindow({\n    frame,\n    viewportBottom,\n    viewportTop,\n  });\n  if (!lineWindow) {\n    patchKeyedDomChildren({\n      createElement: () => document.createElement(\"div\"),\n      getKey: () => \"\",\n      items: [],\n      parent: linesNode,\n      updateElement: () => {},\n    });\n    return;\n  }\n\n  const lines = materializeInlineVisibleLines({\n    block,\n    frame,\n    lineWindow,\n    maxWidth: contentWidth,\n    viewportBottom,\n    viewportTop,\n  });\n\n  patchKeyedDomChildren({\n    createElement: () => document.createElement(\"div\"),\n    getKey: (item) => String(item.lineIndex),\n    items: lines.map((line) => ({\n      line,\n      lineIndex: line.lineIndex,\n    })),\n    parent: linesNode,\n    updateElement: (lineRow, item) => {\n      lineRow.className = \"absolute flex w-max items-center gap-0\";\n      lineRow.dataset.lineIndex = String(item.lineIndex);\n      lineRow.dataset.slot = \"text-inline-line\";\n      lineRow.style.height = `${frame.lineHeight}px`;\n      lineRow.style.left = `${16 + frame.contentLeft}px`;\n      lineRow.style.top = `${item.line.top}px`;\n      lineRow.style.transform = `scale(${frame.scale})`;\n      lineRow.style.transformOrigin = \"left top\";\n\n      const renderKey = inlineLineRenderKey(item.line);\n      if (lineRow.dataset.renderKey === renderKey) return;\n      lineRow.dataset.renderKey = renderKey;\n      lineRow.replaceChildren();\n\n      for (const fragment of item.line.fragments) {\n        const node = fragment.href\n          ? document.createElement(\"a\")\n          : document.createElement(\"span\");\n        node.className = fragment.className;\n        node.textContent = fragment.text;\n        node.style.font = fragment.font;\n        node.style.letterSpacing = \"0\";\n        if (fragment.leadingGap > 0) {\n          node.style.marginLeft = `${fragment.leadingGap}px`;\n        }\n        if (node instanceof HTMLAnchorElement && fragment.href) {\n          node.href = fragment.href;\n          if (!isLocalFragmentHref(fragment.href)) {\n            node.rel = \"noopener noreferrer\";\n            node.target = \"_blank\";\n          }\n          if (fragment.title) node.title = fragment.title;\n        }\n        lineRow.append(node);\n      }\n    },\n  });\n}\n\nfunction inlineLineRenderKey(\n  line: ReturnType<typeof materializeInlineVisibleLines>[number],\n) {\n  return [\n    line.top,\n    line.width,\n    ...line.fragments.map((fragment) =>\n      [\n        fragment.className,\n        fragment.font,\n        fragment.href ?? \"\",\n        fragment.leadingGap,\n        fragment.text,\n        fragment.title ?? \"\",\n      ].join(\"\\u0001\"),\n    ),\n  ].join(\"\\u0002\");\n}\n\nfunction renderCodeBlock({\n  block,\n  contentWidth,\n  frame,\n  row,\n  viewportBottom,\n  viewportTop,\n}: {\n  block: PreparedCodeTextBlock;\n  contentWidth: number;\n  frame: CodeTextBlockFrame;\n  row: HTMLDivElement;\n  viewportBottom: number;\n  viewportTop: number;\n}) {\n  const pre = document.createElement(\"pre\");\n  pre.className =\n    \"absolute overflow-hidden rounded-md border bg-muted text-foreground\";\n  pre.style.height = `${frame.height}px`;\n  pre.style.left = `${16 + frame.contentLeft}px`;\n  pre.style.width = `${frame.width}px`;\n\n  const code = document.createElement(\"code\");\n  code.dataset.slot = \"text-code-lines\";\n  patchCodeBlockLines({\n    block,\n    code,\n    contentWidth,\n    frame,\n    viewportBottom,\n    viewportTop,\n  });\n\n  pre.append(code);\n  row.append(pre);\n  appendCodeBlockToolbar({ block, frame, row });\n}\n\nfunction patchCodeBlockLines({\n  block,\n  code,\n  contentWidth,\n  frame,\n  viewportBottom,\n  viewportTop,\n}: {\n  block: PreparedCodeTextBlock;\n  code: HTMLElement;\n  contentWidth: number;\n  frame: CodeTextBlockFrame;\n  viewportBottom: number;\n  viewportTop: number;\n}) {\n  const lineWindow = getCodeVisibleLineWindow({\n    frame,\n    viewportBottom,\n    viewportTop,\n  });\n  if (!lineWindow) {\n    patchKeyedDomChildren({\n      createElement: () => document.createElement(\"span\"),\n      getKey: () => \"\",\n      items: [],\n      parent: code,\n      updateElement: () => {},\n    });\n    return;\n  }\n\n  const lines = materializeCodeVisibleLines({\n    block,\n    contentWidth,\n    frame,\n    lineWindow,\n    viewportBottom,\n    viewportTop,\n  });\n\n  patchKeyedDomChildren({\n    createElement: () => document.createElement(\"span\"),\n    getKey: (item) => String(item.lineIndex),\n    items: lines.map((line) => ({\n      line,\n      lineIndex: line.lineIndex,\n    })),\n    parent: code,\n    updateElement: (span, item) => {\n      span.className = \"absolute font-mono whitespace-pre\";\n      span.dataset.lineIndex = String(item.lineIndex);\n      span.dataset.slot = \"text-code-line\";\n      span.style.font = block.font;\n      span.style.left = \"12px\";\n      span.style.lineHeight = `${frame.lineHeight}px`;\n      span.style.top = `${item.line.top}px`;\n      span.style.transform = `scale(${frame.scale})`;\n      span.style.transformOrigin = \"left top\";\n\n      const renderKey = `${item.line.top}\\u0001${item.line.line.text}`;\n      if (span.dataset.renderKey === renderKey) return;\n      span.dataset.renderKey = renderKey;\n      span.textContent = item.line.line.text;\n    },\n  });\n}\n\nfunction appendCodeBlockToolbar({\n  block,\n  frame,\n  row,\n}: {\n  block: PreparedCodeTextBlock;\n  frame: CodeTextBlockFrame;\n  row: HTMLDivElement;\n}) {\n  const controls = document.createElement(\"div\");\n  controls.className = \"absolute z-10 flex items-center gap-1\";\n  controls.style.left = `${16 + frame.contentLeft + Math.max(0, frame.width - 66)}px`;\n  controls.style.top = \"6px\";\n\n  if (block.language) {\n    const language = document.createElement(\"span\");\n    language.className =\n      \"rounded bg-background/90 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground shadow-sm\";\n    language.textContent = block.language;\n    controls.append(language);\n  }\n\n  const copyButton = document.createElement(\"button\");\n  copyButton.type = \"button\";\n  copyButton.className =\n    \"rounded bg-background/90 p-1 text-muted-foreground shadow-sm transition-colors hover:bg-muted hover:text-foreground\";\n  copyButton.setAttribute(\"aria-label\", \"Copy code block\");\n  appendCopyIcon(copyButton);\n  copyButton.addEventListener(\"click\", () => {\n    void navigator.clipboard?.writeText(block.fallbackText).then(() => {\n      copyButton.setAttribute(\"aria-label\", \"Copied\");\n      copyButton.replaceChildren();\n      appendCheckIcon(copyButton);\n      window.setTimeout(() => {\n        copyButton.setAttribute(\"aria-label\", \"Copy code block\");\n        copyButton.replaceChildren();\n        appendCopyIcon(copyButton);\n      }, 1200);\n    });\n  });\n  controls.append(copyButton);\n  row.append(controls);\n}\n\nfunction appendCopyIcon(parent: HTMLElement) {\n  const svg = createIconSvg();\n  const back = document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\");\n  back.setAttribute(\"x\", \"8\");\n  back.setAttribute(\"y\", \"8\");\n  back.setAttribute(\"width\", \"8\");\n  back.setAttribute(\"height\", \"8\");\n  back.setAttribute(\"rx\", \"1\");\n  const front = document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\");\n  front.setAttribute(\"x\", \"4\");\n  front.setAttribute(\"y\", \"4\");\n  front.setAttribute(\"width\", \"8\");\n  front.setAttribute(\"height\", \"8\");\n  front.setAttribute(\"rx\", \"1\");\n  svg.append(back, front);\n  parent.append(svg);\n}\n\nfunction appendCheckIcon(parent: HTMLElement) {\n  const svg = createIconSvg();\n  svg.classList.add(\"text-emerald-600\", \"dark:text-emerald-400\");\n  const path = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n  path.setAttribute(\"d\", \"m5 10 3 3 7-7\");\n  svg.append(path);\n  parent.append(svg);\n}\n\nfunction createIconSvg() {\n  const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n  svg.setAttribute(\"viewBox\", \"0 0 20 20\");\n  svg.setAttribute(\"fill\", \"none\");\n  svg.setAttribute(\"stroke\", \"currentColor\");\n  svg.setAttribute(\"stroke-width\", \"1.7\");\n  svg.setAttribute(\"stroke-linecap\", \"round\");\n  svg.setAttribute(\"stroke-linejoin\", \"round\");\n  svg.classList.add(\"size-3\");\n  return svg;\n}\n\nfunction renderImageBlock({\n  block,\n  frame,\n  row,\n}: {\n  block: PreparedImageTextBlock;\n  frame: ImageTextBlockFrame;\n  row: HTMLDivElement;\n}) {\n  if (block.src) {\n    const image = document.createElement(\"img\");\n    image.alt = block.alt;\n    image.className = \"absolute rounded-md border bg-muted object-contain\";\n    image.src = block.src;\n    if (block.title) image.title = block.title;\n    image.style.height = `${frame.imageHeight}px`;\n    image.style.left = `${16 + frame.contentLeft}px`;\n    image.style.maxWidth = \"calc(100% - 32px)\";\n    image.style.width = `${frame.imageWidth}px`;\n    row.append(image);\n    return;\n  }\n\n  const placeholder = document.createElement(\"div\");\n  placeholder.className =\n    \"absolute flex items-center rounded-md border bg-muted px-4 text-sm text-muted-foreground\";\n  placeholder.textContent = block.alt;\n  placeholder.setAttribute(\"role\", \"img\");\n  placeholder.setAttribute(\"aria-label\", block.alt);\n  placeholder.style.height = `${frame.imageHeight}px`;\n  placeholder.style.left = `${16 + frame.contentLeft}px`;\n  placeholder.style.width = `${frame.imageWidth}px`;\n  row.append(placeholder);\n}\n\nfunction renderRuleBlock({\n  frame,\n  row,\n}: {\n  frame: RuleTextBlockFrame;\n  row: HTMLDivElement;\n}) {\n  const rule = document.createElement(\"div\");\n  rule.className = \"absolute h-px bg-border\";\n  rule.style.left = `${16 + frame.contentLeft}px`;\n  rule.style.top = `${Math.floor(frame.height / 2)}px`;\n  rule.style.width = `${frame.width}px`;\n  row.append(rule);\n}\n\nfunction renderTableBlock({\n  block,\n  frame,\n  row,\n  viewportBottom,\n  viewportTop,\n}: {\n  block: PreparedTableTextBlock;\n  frame: TableTextBlockFrame;\n  row: HTMLDivElement;\n  viewportBottom: number;\n  viewportTop: number;\n}) {\n  const headerIdPrefix = `markdown-table-${frame.sourceStartLine}-${frame.sourceEndLine}`;\n  const wrapper = document.createElement(\"div\");\n  wrapper.className =\n    \"absolute max-w-[calc(100%-32px)] overflow-hidden rounded-md border\";\n  wrapper.style.height = `${frame.height}px`;\n  wrapper.style.left = `${16 + frame.contentLeft}px`;\n  wrapper.style.width = `${frame.tableWidth}px`;\n\n  const copyButton = document.createElement(\"button\");\n  copyButton.type = \"button\";\n  copyButton.className =\n    \"absolute top-1 right-1 z-10 rounded bg-background/90 px-1.5 py-1 text-[10px] text-muted-foreground shadow-sm transition-colors hover:bg-muted hover:text-foreground\";\n  copyButton.setAttribute(\"aria-label\", \"Copy table\");\n  copyButton.textContent = \"Copy\";\n  copyButton.addEventListener(\"click\", () => {\n    void navigator.clipboard?.writeText(\n      serializeMarkdownTableForClipboard(block),\n    );\n  });\n  wrapper.append(copyButton);\n\n  const scroller = document.createElement(\"div\");\n  scroller.className = \"h-full overflow-x-auto\";\n\n  const table = document.createElement(\"table\");\n  table.className = \"border-collapse text-left text-[13px]\";\n  table.style.width = `${frame.tableWidth}px`;\n\n  const colgroup = document.createElement(\"colgroup\");\n  for (const width of frame.columnWidths) {\n    const col = document.createElement(\"col\");\n    col.style.width = `${width}px`;\n    colgroup.append(col);\n  }\n  table.append(colgroup);\n\n  const thead = document.createElement(\"thead\");\n  thead.className = \"bg-muted\";\n  const headerRow = document.createElement(\"tr\");\n  headerRow.style.height = `${frame.headerHeight}px`;\n  for (let index = 0; index < block.header.length; index++) {\n    const th = document.createElement(\"th\");\n    th.className = \"border-b px-3.5 py-2 font-semibold text-foreground\";\n    th.id = `${headerIdPrefix}-column-${index}`;\n    th.scope = \"col\";\n    th.style.textAlign = block.alignments[index] ?? \"left\";\n    appendTableCellContent(th, block.header[index]);\n    headerRow.append(th);\n  }\n  thead.append(headerRow);\n  table.append(thead);\n\n  const tbody = document.createElement(\"tbody\");\n  tbody.dataset.slot = \"text-table-body\";\n  patchTableBodyRows({\n    block,\n    frame,\n    tbody,\n    viewportBottom,\n    viewportTop,\n  });\n  table.append(tbody);\n  scroller.append(table);\n  wrapper.append(scroller);\n  row.append(wrapper);\n}\n\ntype TableBodyProjectionItem =\n  | {\n      height: number;\n      kind: \"spacer\";\n      slot: \"after\" | \"before\";\n    }\n  | {\n      kind: \"row\";\n      rowIndex: number;\n    };\n\nfunction patchTableBodyRows({\n  block,\n  frame,\n  tbody,\n  viewportBottom,\n  viewportTop,\n}: {\n  block: PreparedTableTextBlock;\n  frame: TableTextBlockFrame;\n  tbody: HTMLTableSectionElement;\n  viewportBottom: number;\n  viewportTop: number;\n}) {\n  const rowWindow = getTableVisibleRowWindow({\n    frame,\n    viewportBottom,\n    viewportTop,\n  });\n  const items: TableBodyProjectionItem[] = [];\n  if (rowWindow.beforeHeight > 0) {\n    items.push({\n      height: rowWindow.beforeHeight,\n      kind: \"spacer\",\n      slot: \"before\",\n    });\n  }\n  for (\n    let rowIndex = rowWindow.startIndex;\n    rowIndex < rowWindow.endIndex;\n    rowIndex++\n  ) {\n    items.push({ kind: \"row\", rowIndex });\n  }\n  if (rowWindow.afterHeight > 0) {\n    items.push({\n      height: rowWindow.afterHeight,\n      kind: \"spacer\",\n      slot: \"after\",\n    });\n  }\n\n  const headerIdPrefix = `markdown-table-${frame.sourceStartLine}-${frame.sourceEndLine}`;\n  patchKeyedDomChildren({\n    createElement: () => document.createElement(\"tr\"),\n    getKey: (item) =>\n      item.kind === \"spacer\" ? `spacer:${item.slot}` : `row:${item.rowIndex}`,\n    items,\n    parent: tbody,\n    updateElement: (tableRow, item) => {\n      if (item.kind === \"spacer\") {\n        updateTableSpacerRow(tableRow, item, block.header.length);\n        return;\n      }\n\n      updateTableDataRow({\n        alignments: block.alignments,\n        cellCount: block.header.length,\n        frame,\n        headerIdPrefix,\n        row: tableRow,\n        rowIndex: item.rowIndex,\n        sourceRow: block.rows[item.rowIndex] ?? [],\n      });\n    },\n  });\n}\n\nfunction updateTableSpacerRow(\n  row: HTMLTableRowElement,\n  item: Extract<TableBodyProjectionItem, { kind: \"spacer\" }>,\n  colSpan: number,\n) {\n  row.dataset.slot = \"text-table-spacer\";\n  delete row.dataset.rowIndex;\n  delete row.dataset.sourceLine;\n  row.setAttribute(\"aria-hidden\", \"true\");\n  row.style.height = `${item.height}px`;\n\n  const renderKey = `spacer:${item.height}:${colSpan}`;\n  if (row.dataset.renderKey === renderKey) return;\n  row.dataset.renderKey = renderKey;\n  const cell = document.createElement(\"td\");\n  cell.colSpan = colSpan || 1;\n  row.replaceChildren(cell);\n}\n\nfunction updateTableDataRow({\n  alignments,\n  cellCount,\n  frame,\n  headerIdPrefix,\n  row,\n  rowIndex,\n  sourceRow,\n}: {\n  alignments: PreparedTableTextBlock[\"alignments\"];\n  cellCount: number;\n  frame: TableTextBlockFrame;\n  headerIdPrefix: string;\n  row: HTMLTableRowElement;\n  rowIndex: number;\n  sourceRow: PreparedTableCell[];\n}) {\n  row.dataset.rowIndex = String(rowIndex);\n  row.dataset.slot = \"text-table-row\";\n  row.dataset.sourceLine = String(frame.rowSourceStartLines[rowIndex]);\n  row.removeAttribute(\"aria-hidden\");\n  row.style.height = `${frame.rowHeights[rowIndex] ?? 0}px`;\n\n  const renderKey = tableDataRowRenderKey({\n    alignments,\n    cellCount,\n    frame,\n    rowIndex,\n    sourceRow,\n  });\n  if (row.dataset.renderKey === renderKey) return;\n  row.dataset.renderKey = renderKey;\n  row.replaceChildren();\n\n  for (let cellIndex = 0; cellIndex < cellCount; cellIndex++) {\n    const td = document.createElement(\"td\");\n    td.className = \"border-t px-3.5 py-1.5 align-top text-foreground\";\n    td.headers = `${headerIdPrefix}-column-${cellIndex}`;\n    td.style.textAlign = alignments[cellIndex] ?? \"left\";\n    appendTableCellContent(td, sourceRow[cellIndex]);\n    row.append(td);\n  }\n}\n\nfunction tableDataRowRenderKey({\n  alignments,\n  cellCount,\n  frame,\n  rowIndex,\n  sourceRow,\n}: {\n  alignments: PreparedTableTextBlock[\"alignments\"];\n  cellCount: number;\n  frame: TableTextBlockFrame;\n  rowIndex: number;\n  sourceRow: PreparedTableCell[];\n}) {\n  const cells = Array.from({ length: cellCount }, (_, cellIndex) => {\n    const cell = sourceRow[cellIndex];\n    return [\n      alignments[cellIndex] ?? \"left\",\n      cell?.className ?? \"\",\n      cell?.href ?? \"\",\n      cell?.text ?? \"\",\n      cell?.title ?? \"\",\n    ].join(\"\\u0001\");\n  });\n  return [\n    rowIndex,\n    frame.rowHeights[rowIndex] ?? 0,\n    frame.rowSourceStartLines[rowIndex] ?? \"\",\n    ...cells,\n  ].join(\"\\u0002\");\n}\n\nfunction appendTableCellContent(\n  parent: HTMLElement,\n  cell: PreparedTableCell | undefined,\n) {\n  if (!cell) return;\n  const node = cell.href\n    ? document.createElement(\"a\")\n    : document.createElement(\"span\");\n  node.className = `wrap-break-word ${cell.className}`;\n  node.textContent = cell.text;\n  if (node instanceof HTMLAnchorElement && cell.href) {\n    node.href = cell.href;\n    if (!isLocalFragmentHref(cell.href)) {\n      node.rel = \"noopener noreferrer\";\n      node.target = \"_blank\";\n    }\n    if (cell.title) node.title = cell.title;\n  }\n  parent.append(node);\n}\n\nfunction appendBlockChrome(row: HTMLDivElement, frame: TextBlockFrame) {\n  for (const left of frame.quoteRailLefts) {\n    const rail = document.createElement(\"div\");\n    rail.className = \"absolute top-0 bottom-0 w-[3px] rounded-full bg-border\";\n    rail.style.left = `${16 + left}px`;\n    rail.setAttribute(\"aria-hidden\", \"true\");\n    row.append(rail);\n  }\n\n  if (!frame.markerText || frame.markerLeft == null) return;\n\n  const marker = document.createElement(\"span\");\n  marker.className = `absolute font-mono text-xs whitespace-pre ${frame.markerClassName ?? \"\"}`;\n  marker.textContent = frame.markerText;\n  marker.style.left = `${16 + frame.markerLeft}px`;\n  marker.style.top =\n    frame.kind === \"inline\"\n      ? `${Math.max(0, Math.round((frame.lineHeight - 12) / 2))}px`\n      : \"10px\";\n  marker.setAttribute(\"aria-hidden\", \"true\");\n  row.append(marker);\n}\n\nfunction localFragmentHrefFromEventTarget(target: EventTarget | null) {\n  if (!(target instanceof Element)) return null;\n  const link = target.closest<HTMLAnchorElement>('a[href^=\"#\"]');\n  const href = link?.getAttribute(\"href\") ?? null;\n  return href && href.length > 1 ? href : null;\n}\n\nfunction decodeMarkdownFragmentHref(href: string) {\n  try {\n    return decodeURIComponent(href.slice(1));\n  } catch {\n    return href.slice(1);\n  }\n}\n\nfunction markdownHeadingBlockIndex(\n  blocks: readonly PreparedTextBlock[],\n  headingId: string,\n) {\n  return blocks.findIndex((block) => {\n    return block.kind === \"inline\" && block.headingId === headingId;\n  });\n}\n\nfunction isLocalFragmentHref(href: string) {\n  return href.startsWith(\"#\");\n}\n\nfunction textFrameIsHighlighted(\n  frame: TextBlockFrame,\n  highlightRange: ReturnType<typeof normalizeTextLineRange>,\n) {\n  return frame.sourceStartLine === frame.sourceEndLine\n    ? isLineInRange(frame.sourceStartLine, highlightRange)\n    : textFrameIntersectsLineRange({ frame, range: highlightRange });\n}\n\nfunction blockVisibleWindowKey(\n  frame: TextBlockFrame,\n  viewportTop: number,\n  viewportBottom: number,\n) {\n  switch (frame.kind) {\n    case \"inline\": {\n      const lineWindow = getInlineVisibleLineWindow({\n        frame,\n        viewportBottom,\n        viewportTop,\n      });\n      return lineWindow\n        ? `${lineWindow.firstLine}:${lineWindow.lastLine}`\n        : \"none\";\n    }\n    case \"code\": {\n      const lineWindow = getCodeVisibleLineWindow({\n        frame,\n        viewportBottom,\n        viewportTop,\n      });\n      return lineWindow\n        ? `${lineWindow.firstLine}:${lineWindow.lastLine}`\n        : \"none\";\n    }\n    case \"table\": {\n      const rowWindow = getTableVisibleRowWindow({\n        frame,\n        viewportBottom,\n        viewportTop,\n      });\n      return `${rowWindow.startIndex}:${rowWindow.endIndex}`;\n    }\n    case \"image\":\n    case \"rule\":\n      return \"static\";\n  }\n}\n\nfunction useTextViewerFontEpoch() {\n  const [fontEpoch, setFontEpoch] = React.useState(0);\n\n  useMountEffect(() => {\n    const fonts = document.fonts;\n    if (!fonts) return;\n\n    let isMounted = true;\n    void fonts.ready.then(() => {\n      if (isMounted) setFontEpoch((epoch) => epoch + 1);\n    });\n\n    return () => {\n      isMounted = false;\n    };\n  });\n\n  return fontEpoch;\n}\n",
      "type": "registry:ui",
      "target": "@ui/text-viewer-chenglou-content.tsx"
    }
  ],
  "type": "registry:ui"
}