Skip to content

armgit / ui

Public Imported from GitHub
0
TypeScript

Improve code block scroll reset and theme handling

Andrew Luo4d6adc3d2681
diff --git a/apps/v4/components/highlighted-code-block.tsx b/apps/v4/components/highlighted-code-block.tsx
index 88696fd..630a263 100644
--- a/apps/v4/components/highlighted-code-block.tsx
+++ b/apps/v4/components/highlighted-code-block.tsx
@@ -227,6 +227,12 @@ function handleCodeBlockWheel(event: WheelEvent, container: HTMLElement) {
})
}
+function resetCodeBlockScroll(container: HTMLElement | null) {
+ container
+ ?.querySelector<HTMLElement>(".no-scrollbar")
+ ?.scrollTo({ top: 0, left: 0, behavior: "auto" })
+}
+
export function HighlightedCodeBlock({
code,
className,
@@ -238,6 +244,7 @@ export function HighlightedCodeBlock({
previewLines,
renderFallbackCode = false,
showCopy = true,
+ scrollResetKey,
}: {
code: string
className?: string
@@ -249,6 +256,7 @@ export function HighlightedCodeBlock({
previewLines?: number
renderFallbackCode?: boolean
showCopy?: boolean
+ scrollResetKey?: React.Key
}) {
const [isVisible, setIsVisible] = React.useState(!lazy)
const [renderedCodeKey, setRenderedCodeKey] = React.useState<string | null>(
@@ -256,6 +264,7 @@ export function HighlightedCodeBlock({
)
const codeThemeType = useCodeThemeType()
const containerRef = React.useRef<HTMLDivElement | null>(null)
+ const pendingScrollResetKeyRef = React.useRef<string | null>(null)
const visibleCode = React.useMemo(() => {
return getPreviewCode(code, previewLines)
}, [code, previewLines])
@@ -272,10 +281,41 @@ export function HighlightedCodeBlock({
[fileName, language, visibleCode]
)
const codeRenderKey = `${file.cacheKey}:${codeThemeType}`
+ const virtualizerKey =
+ scrollResetKey === undefined
+ ? codeRenderKey
+ : `${codeRenderKey}:${String(scrollResetKey)}`
const hasRenderedCode = renderedCodeKey === codeRenderKey
const shouldShowFallback =
renderFallbackCode && isVisible && !hasRenderedCode
+ React.useLayoutEffect(() => {
+ setRenderedCodeKey(null)
+ pendingScrollResetKeyRef.current = codeRenderKey
+
+ const container = containerRef.current
+
+ resetCodeBlockScroll(container)
+ const frameId = window.requestAnimationFrame(() => {
+ resetCodeBlockScroll(container)
+ })
+
+ return () => window.cancelAnimationFrame(frameId)
+ }, [codeRenderKey])
+
+ React.useLayoutEffect(() => {
+ if (scrollResetKey === undefined) return
+
+ const container = containerRef.current
+
+ resetCodeBlockScroll(container)
+ const frameId = window.requestAnimationFrame(() => {
+ resetCodeBlockScroll(container)
+ })
+
+ return () => window.cancelAnimationFrame(frameId)
+ }, [scrollResetKey])
+
const fileOptions = React.useMemo(
() => ({
disableFileHeader: true,
@@ -287,6 +327,13 @@ export function HighlightedCodeBlock({
themeType: codeThemeType,
onPostRender: (fileContainer: HTMLElement) => {
syncVirtualizerBuffers(fileContainer, lastRenderableLineIndex)
+ if (pendingScrollResetKeyRef.current === codeRenderKey) {
+ resetCodeBlockScroll(containerRef.current)
+ window.requestAnimationFrame(() => {
+ resetCodeBlockScroll(containerRef.current)
+ })
+ pendingScrollResetKeyRef.current = null
+ }
setRenderedCodeKey(codeRenderKey)
},
unsafeCSS: CODE_FILE_UNSAFE_CSS,
@@ -375,6 +422,7 @@ export function HighlightedCodeBlock({
highlighterOptions={CODE_HIGHLIGHTER_OPTIONS}
>
<Virtualizer
+ key={virtualizerKey}
className={cn(
"no-scrollbar min-w-0 overflow-x-auto overflow-y-auto overscroll-contain outline-none",
maxHeightClassName
@@ -382,6 +430,7 @@ export function HighlightedCodeBlock({
contentClassName="min-w-full"
>
<File
+ key={codeRenderKey}
file={file}
metrics={CODE_VIRTUAL_FILE_METRICS}
style={CODE_FILE_THEME}
diff --git a/apps/v4/components/human-review-docs.tsx b/apps/v4/components/human-review-docs.tsx
index 7e94be0..43b0bbc 100644
--- a/apps/v4/components/human-review-docs.tsx
+++ b/apps/v4/components/human-review-docs.tsx
@@ -159,36 +159,6 @@ const BLOCK_REVIEW_PDF_URL = "/samples/bank-statement-x4uhhi7t.pdf"
const DEFAULT_ZOOM = 0.75
const REVIEW_HIGHLIGHT_STYLE =
"border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"
-const DIFF_VIEWER_THEME = {
- "--diffs-light-bg": "oklch(0.985 0.002 247)",
- "--diffs-dark-bg": "oklch(0.18 0.003 247)",
- "--diffs-light": "oklch(0.22 0.01 247)",
- "--diffs-dark": "oklch(0.92 0.006 247)",
- "--diffs-bg-context-override":
- "light-dark(oklch(0.967 0.003 247), oklch(0.235 0.004 247))",
- "--diffs-bg-context-gutter-override":
- "light-dark(oklch(0.948 0.004 247), oklch(0.205 0.004 247))",
- "--diffs-bg-separator-override":
- "light-dark(oklch(0.94 0.004 247), oklch(0.255 0.005 247))",
- "--diffs-bg-buffer-override":
- "light-dark(oklch(0.955 0.004 247), oklch(0.225 0.004 247))",
- "--diffs-light-addition-color": "oklch(0.54 0.13 158)",
- "--diffs-dark-addition-color": "oklch(0.72 0.13 158)",
- "--diffs-light-deletion-color": "oklch(0.55 0.16 28)",
- "--diffs-dark-deletion-color": "oklch(0.72 0.14 28)",
- "--diffs-bg-addition-override":
- "light-dark(oklch(0.957 0.032 158), oklch(0.255 0.052 158))",
- "--diffs-bg-addition-emphasis-override":
- "light-dark(oklch(0.88 0.06 158), oklch(0.36 0.08 158))",
- "--diffs-bg-deletion-override":
- "light-dark(oklch(0.958 0.03 28), oklch(0.255 0.047 28))",
- "--diffs-bg-deletion-emphasis-override":
- "light-dark(oklch(0.9 0.052 28), oklch(0.36 0.075 28))",
- "--diffs-fg-number-override":
- "light-dark(oklch(0.56 0.018 247), oklch(0.66 0.012 247))",
- "--diffs-font-size": "12px",
- "--diffs-line-height": "20px",
-} as React.CSSProperties
function readIsDarkTheme() {
return (
@@ -2446,13 +2416,12 @@ function JsonDiffView({
return (
<Virtualizer
- className="h-full overflow-auto rounded-b-xl bg-surface/60"
+ className="h-full overflow-auto bg-surface/60"
contentClassName="min-w-full"
>
<div className="human-review-diff h-full text-xs">
<MultiFileDiff
className="block min-w-full"
- style={DIFF_VIEWER_THEME}
oldFile={oldFile}
newFile={newFile}
options={{
@@ -2858,7 +2827,7 @@ export function HumanReviewExample() {
}`
const humanReviewSourceCode =
- '"use client"\n\nimport * as React from "react"\nimport {\n DataEditor,\n emptyGridSelection,\n GridCellKind,\n TextCellEntry,\n type EditableGridCell,\n type GridCell,\n type GridColumn,\n type GridMouseEventArgs,\n type GridSelection,\n type Item,\n type NumberCell,\n type ProvideEditorComponent,\n type Rectangle,\n type TextCell,\n type Theme,\n} from "@glideapps/glide-data-grid"\nimport {\n ArrowLeft01Icon,\n CancelCircleIcon,\n InputNumericIcon,\n InputTextIcon,\n SecondBracketIcon,\n SourceCodeSquareIcon,\n TextCheckIcon,\n Undo02Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { MultiFileDiff, Virtualizer } from "@pierre/diffs/react"\nimport { flushSync } from "react-dom"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/registry/new-york-v4/ui/button"\nimport { Input } from "@/registry/new-york-v4/ui/input"\nimport { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"\nimport {\n Tabs,\n TabsContent,\n TabsList,\n TabsTrigger,\n} from "@/registry/new-york-v4/ui/tabs"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nimport "@glideapps/glide-data-grid/dist/index.css"\n\nexport type JsonPrimitive = string | number | boolean | null\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray\nexport type JsonObject = { [key: string]: JsonValue }\nexport type JsonArray = JsonValue[]\nexport type SchemaPropertyType =\n | "string"\n | "number"\n | "integer"\n | "boolean"\n | "object"\n | "array"\n\nexport type ReviewFieldSchema = {\n type: SchemaPropertyType\n title?: string\n description?: string\n enum?: Array<string | number>\n properties?: Record<string, ReviewFieldSchema>\n items?: ReviewFieldSchema\n}\n\nexport type HighlightArea = {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport type ReviewField = {\n key: string\n schema: ReviewFieldSchema\n actual: JsonValue\n expected: JsonValue\n location?: ReviewLocation\n metadataPath?: string\n}\n\nexport type ReviewLocation = {\n page: number\n area: HighlightArea\n}\n\nexport type ReviewCitation = {\n page: number\n polygon?: Array<{ x: number; y: number }>\n pageWidth: number\n pageHeight: number\n}\n\nexport type ReviewMetadataEntry = {\n citations?: ReviewCitation[]\n}\n\nconst DEFAULT_ZOOM = 0.75\nconst REVIEW_HIGHLIGHT_STYLE =\n "border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"\nconst DIFF_VIEWER_THEME = {\n "--diffs-light-bg": "oklch(0.985 0.002 247)",\n "--diffs-dark-bg": "oklch(0.18 0.003 247)",\n "--diffs-light": "oklch(0.22 0.01 247)",\n "--diffs-dark": "oklch(0.92 0.006 247)",\n "--diffs-bg-context-override":\n "light-dark(oklch(0.967 0.003 247), oklch(0.235 0.004 247))",\n "--diffs-bg-context-gutter-override":\n "light-dark(oklch(0.948 0.004 247), oklch(0.205 0.004 247))",\n "--diffs-bg-separator-override":\n "light-dark(oklch(0.94 0.004 247), oklch(0.255 0.005 247))",\n "--diffs-bg-buffer-override":\n "light-dark(oklch(0.955 0.004 247), oklch(0.225 0.004 247))",\n "--diffs-light-addition-color": "oklch(0.54 0.13 158)",\n "--diffs-dark-addition-color": "oklch(0.72 0.13 158)",\n "--diffs-light-deletion-color": "oklch(0.55 0.16 28)",\n "--diffs-dark-deletion-color": "oklch(0.72 0.14 28)",\n "--diffs-bg-addition-override":\n "light-dark(oklch(0.957 0.032 158), oklch(0.255 0.052 158))",\n "--diffs-bg-addition-emphasis-override":\n "light-dark(oklch(0.88 0.06 158), oklch(0.36 0.08 158))",\n "--diffs-bg-deletion-override":\n "light-dark(oklch(0.958 0.03 28), oklch(0.255 0.047 28))",\n "--diffs-bg-deletion-emphasis-override":\n "light-dark(oklch(0.9 0.052 28), oklch(0.36 0.075 28))",\n "--diffs-fg-number-override":\n "light-dark(oklch(0.56 0.018 247), oklch(0.66 0.012 247))",\n "--diffs-font-size": "12px",\n "--diffs-line-height": "20px",\n} as React.CSSProperties\n\nfunction readIsDarkTheme() {\n return (\n typeof document !== "undefined" &&\n document.documentElement.classList.contains("dark")\n )\n}\n\n// A single shared MutationObserver backs every consumer. Each grid previously\n// created its own observer (two, via useHumanReviewGridTheme), so opening a\n// nested array view spun up and tore down several observers at once.\nconst darkThemeListeners = new Set<(isDark: boolean) => void>()\nlet darkThemeObserver: MutationObserver | null = null\nlet sharedIsDarkTheme = false\n\nfunction ensureDarkThemeObserver() {\n if (\n darkThemeObserver ||\n typeof document === "undefined" ||\n typeof MutationObserver === "undefined"\n ) {\n return\n }\n\n sharedIsDarkTheme = readIsDarkTheme()\n darkThemeObserver = new MutationObserver(() => {\n const nextIsDark = readIsDarkTheme()\n if (nextIsDark === sharedIsDarkTheme) return\n\n sharedIsDarkTheme = nextIsDark\n darkThemeListeners.forEach((listener) => listener(nextIsDark))\n })\n darkThemeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ["class"],\n })\n}\n\nfunction useIsDarkTheme() {\n const [isDark, setIsDark] = React.useState(readIsDarkTheme)\n\n React.useEffect(() => {\n ensureDarkThemeObserver()\n setIsDark(sharedIsDarkTheme)\n darkThemeListeners.add(setIsDark)\n\n return () => {\n darkThemeListeners.delete(setIsDark)\n if (darkThemeListeners.size === 0 && darkThemeObserver) {\n darkThemeObserver.disconnect()\n darkThemeObserver = null\n }\n }\n }, [])\n\n return isDark\n}\n\nfunction useHumanReviewGridTheme() {\n const isDark = useIsDarkTheme()\n\n return React.useMemo<Partial<Theme>>(\n () => ({\n accentColor: isDark ? "rgb(96, 165, 250)" : "rgb(37, 99, 235)",\n accentLight: isDark ? "rgba(29, 78, 216, 0.15)" : "rgb(219, 234, 254)",\n accentFg: "rgb(255, 255, 255)",\n textDark: isDark ? "rgb(229, 229, 229)" : "rgb(23, 23, 23)",\n textMedium: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n textLight: isDark ? "rgb(115, 115, 115)" : "rgb(163, 163, 163)",\n textBubble: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n textHeader: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n textGroupHeader: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n bgCell: isDark ? "rgb(10, 10, 10)" : "rgb(255, 255, 255)",\n bgCellMedium: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n bgHeader: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n bgHeaderHasFocus: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n bgHeaderHovered: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n borderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n horizontalBorderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n cellHorizontalPadding: 8,\n cellVerticalPadding: 3,\n headerIconSize: 18,\n baseFontStyle: "13px",\n headerFontStyle: "600 13px",\n markerFontStyle: "11px",\n fontFamily: \'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif\',\n editorFontSize: "13px",\n }),\n [isDark]\n )\n}\n\nexport const REVIEW_FIELDS: ReviewField[] = [\n {\n key: "statement_period",\n schema: {\n type: "string",\n title: "Statement period",\n description: "Date range covered by the bank statement.",\n },\n actual: "Jan 1-31, 2026",\n expected: "January 1-31, 2026",\n location: {\n page: 1,\n area: { left: 31, top: 30, width: 40, height: 5.8 },\n },\n },\n {\n key: "transactions",\n schema: {\n type: "array",\n title: "Transactions",\n description: "Posted account activity during the statement period.",\n items: {\n type: "object",\n properties: {\n date: {\n type: "string",\n title: "Date",\n },\n description: {\n type: "string",\n title: "Description",\n },\n amount: {\n type: "number",\n title: "Amount",\n },\n category: {\n type: "string",\n title: "Category",\n },\n merchant: {\n type: "object",\n title: "Merchant",\n properties: {\n name: {\n type: "string",\n title: "Name",\n },\n city: {\n type: "string",\n title: "City",\n },\n risk_level: {\n type: "string",\n title: "Risk level",\n },\n },\n },\n tags: {\n type: "array",\n title: "Tags",\n items: {\n type: "string",\n title: "Tag",\n },\n },\n },\n },\n },\n actual: [\n {\n date: "2026-01-03",\n description: "ACH CREDIT PAYROLL",\n amount: 4250,\n category: "Deposit",\n merchant: {\n name: "Acme Payroll",\n city: "New York",\n risk_level: "low",\n },\n tags: ["payroll", "recurring"],\n },\n {\n date: "2026-01-12",\n description: "POS PURCHASE GROCERY MART",\n amount: -86.42,\n category: "Debit",\n merchant: {\n name: "Grocery Mart",\n city: "Brooklyn",\n risk_level: "medium",\n },\n tags: ["card", "groceries"],\n },\n ],\n expected: [\n {\n date: "2026-01-03",\n description: "ACH CREDIT PAYROLL",\n amount: 4250,\n category: "Deposit",\n merchant: {\n name: "Acme Payroll",\n city: "New York",\n risk_level: "low",\n },\n tags: ["payroll", "recurring"],\n },\n {\n date: "2026-01-12",\n description: "POS PURCHASE GROCERY MART",\n amount: -68.42,\n category: "Debit",\n merchant: {\n name: "Grocery Mart",\n city: "Brooklyn",\n risk_level: "low",\n },\n tags: ["card", "groceries", "needs_review"],\n },\n ],\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "ending_balance",\n schema: {\n type: "number",\n title: "Ending balance",\n description: "Final account balance at the end of the statement period.",\n },\n actual: 12840.18,\n expected: 12858.18,\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "overdraft_protection_enabled",\n schema: {\n type: "boolean",\n title: "Overdraft protection enabled",\n description: "Whether overdraft protection is enabled for the account.",\n },\n actual: false,\n expected: true,\n location: {\n page: 2,\n area: { left: 9.5, top: 12, width: 81, height: 11.5 },\n },\n },\n {\n key: "account_details",\n schema: {\n type: "object",\n title: "Account details",\n description: "Account owner and identifying details from the statement.",\n properties: {\n holder_name: {\n type: "string",\n title: "Holder name",\n },\n account_last_four: {\n type: "string",\n title: "Account last four",\n },\n account_type: {\n type: "string",\n title: "Account type",\n },\n mailing_address: {\n type: "object",\n title: "Mailing address",\n properties: {\n line_1: {\n type: "string",\n title: "Line 1",\n },\n city: {\n type: "string",\n title: "City",\n },\n state: {\n type: "string",\n title: "State",\n },\n },\n },\n linked_accounts: {\n type: "array",\n title: "Linked accounts",\n items: {\n type: "object",\n properties: {\n nickname: {\n type: "string",\n title: "Nickname",\n },\n last_four: {\n type: "string",\n title: "Last four",\n },\n },\n },\n },\n },\n },\n actual: {\n holder_name: "Jordan Lee",\n account_last_four: "4821",\n account_type: "Checking",\n mailing_address: {\n line_1: "42 Market Street",\n city: "Brooklyn",\n state: "NY",\n },\n linked_accounts: [\n {\n nickname: "Operations reserve",\n last_four: "1842",\n },\n ],\n },\n expected: {\n holder_name: "Jordan Lee",\n account_last_four: "4821",\n account_type: "Premier Checking",\n mailing_address: {\n line_1: "42 Market Street",\n city: "New York",\n state: "NY",\n },\n linked_accounts: [\n {\n nickname: "Operations reserve",\n last_four: "1842",\n },\n {\n nickname: "Payroll sweep",\n last_four: "9174",\n },\n ],\n },\n },\n]\n\nfunction getCitationLocation(\n citation: ReviewCitation\n): ReviewLocation | undefined {\n const polygon = citation.polygon\n if (!polygon?.length || !citation.pageWidth || !citation.pageHeight) {\n return undefined\n }\n\n const xs = polygon.map((point) => point.x)\n const ys = polygon.map((point) => point.y)\n const left = Math.min(...xs)\n const top = Math.min(...ys)\n const right = Math.max(...xs)\n const bottom = Math.max(...ys)\n\n return {\n page: citation.page,\n area: {\n left: (left / citation.pageWidth) * 100,\n top: (top / citation.pageHeight) * 100,\n width: ((right - left) / citation.pageWidth) * 100,\n height: ((bottom - top) / citation.pageHeight) * 100,\n },\n }\n}\n\nexport function getMetadataLocation(\n metadata: Record<string, ReviewMetadataEntry> | undefined,\n metadataPath: string | undefined\n) {\n if (!metadata || !metadataPath) return undefined\n\n const citation = metadata[metadataPath]?.citations?.find(\n (candidate) => candidate.polygon?.length\n )\n\n return citation ? getCitationLocation(citation) : undefined\n}\n\nexport function getReviewFieldLocation(\n field: ReviewField | undefined,\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n) {\n if (!field) return undefined\n\n return (\n field.location ??\n resolveLocation?.(field.metadataPath ?? field.key) ??\n undefined\n )\n}\n\nexport function getReviewLocationKey(location: ReviewLocation | undefined) {\n if (!location) return null\n\n const { area } = location\n return [location.page, area.left, area.top, area.width, area.height].join(":")\n}\n\nfunction valuesFromFields(\n fields: ReviewField[],\n valueKey: "actual" | "expected"\n) {\n return fields.reduce<JsonObject>((values, field) => {\n values[field.key] = field[valueKey]\n return values\n }, {})\n}\n\nfunction formatJson(value: unknown) {\n return JSON.stringify(value, null, 2)\n}\n\nfunction isJsonObject(value: JsonValue): value is JsonObject {\n return typeof value === "object" && value !== null && !Array.isArray(value)\n}\n\nfunction isJsonArray(value: JsonValue): value is JsonArray {\n return Array.isArray(value)\n}\n\nfunction getObjectValue(value: JsonValue, key: string): JsonValue {\n if (!isJsonObject(value)) return null\n return value[key] ?? null\n}\n\nfunction setObjectValue(\n value: JsonValue,\n key: string,\n childValue: JsonValue\n): JsonObject {\n return {\n ...(isJsonObject(value) ? value : {}),\n [key]: childValue,\n }\n}\n\nfunction getArrayValue(value: JsonValue): JsonArray {\n return isJsonArray(value) ? value : []\n}\n\nfunction setArrayItemValue(\n value: JsonValue,\n index: number,\n childValue: JsonValue\n): JsonArray {\n const nextValue = getArrayValue(value).slice()\n nextValue[index] = childValue\n return nextValue\n}\n\nfunction getPrimitiveValue(value: JsonValue): JsonPrimitive {\n return isJsonObject(value) || isJsonArray(value) ? null : value\n}\n\nfunction jsonValuesEqual(left: JsonValue, right: JsonValue) {\n return formatJson(left) === formatJson(right)\n}\n\nexport function findReviewField(\n fields: ReviewField[],\n fieldKey: string | undefined\n): ReviewField | undefined {\n if (!fieldKey) return undefined\n\n for (const field of fields) {\n if (field.key === fieldKey) return field\n\n if (field.schema.type === "object") {\n const childFields = Object.entries(field.schema.properties ?? {}).map(\n ([key, schema]): ReviewField => ({\n key: `${field.key}.${key}`,\n schema,\n actual: getObjectValue(field.actual, key),\n expected: getObjectValue(field.expected, key),\n metadataPath: `${field.metadataPath ?? field.key}.${key}`,\n })\n )\n const childField = findReviewField(childFields, fieldKey)\n if (childField) return childField\n }\n }\n\n return undefined\n}\n\nfunction formatValue(value: JsonValue) {\n if (value === null) return "NULL"\n if (isJsonObject(value) || isJsonArray(value)) return formatJson(value)\n if (typeof value === "boolean") return value ? "true" : "false"\n return String(value)\n}\n\nfunction areGridRangesEqual(\n left: Readonly<Rectangle> | undefined,\n right: Readonly<Rectangle> | undefined\n) {\n return (\n left === right ||\n (left !== undefined &&\n right !== undefined &&\n left.x === right.x &&\n left.y === right.y &&\n left.width === right.width &&\n left.height === right.height)\n )\n}\n\nfunction areGridRangeStacksEqual(\n left: readonly Readonly<Rectangle>[] | undefined,\n right: readonly Readonly<Rectangle>[] | undefined\n) {\n if (left === right) return true\n if (!left || !right || left.length !== right.length) return false\n\n return left.every((range, index) => areGridRangesEqual(range, right[index]))\n}\n\nfunction areGridSelectionsEqual(left: GridSelection, right: GridSelection) {\n const leftCurrent = left.current\n const rightCurrent = right.current\n\n return (\n leftCurrent?.cell[0] === rightCurrent?.cell[0] &&\n leftCurrent?.cell[1] === rightCurrent?.cell[1] &&\n areGridRangesEqual(leftCurrent?.range, rightCurrent?.range) &&\n areGridRangeStacksEqual(\n leftCurrent?.rangeStack,\n rightCurrent?.rangeStack\n ) &&\n left.columns.equals(right.columns) &&\n left.rows.equals(right.rows)\n )\n}\n\nfunction getGridSelectionRanges(selection: GridSelection | undefined) {\n const current = selection?.current\n if (!current) return []\n\n return [...(current.rangeStack ?? []), current.range]\n}\n\nfunction areArrayNestedViewsEqual(\n left: ArrayNestedView[],\n right: ArrayNestedView[]\n) {\n if (left === right) return true\n if (left.length !== right.length) return false\n\n return left.every((view, index) => {\n const other = right[index]\n\n return (\n view.rowIndex === other?.rowIndex &&\n view.columnId === other.columnId &&\n view.title === other.title &&\n view.schema === other.schema &&\n Object.is(view.value, other.value)\n )\n })\n}\n\ntype HumanReviewOverlayCell = TextCell | NumberCell\n\ntype HumanReviewTextOverlayEditorProps = React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n> & {\n overlayOpenRef: React.RefObject<boolean>\n readOnly?: boolean\n}\n\nfunction HumanReviewTextOverlayEditor({\n isHighlighted,\n onFinishedEditing,\n overlayOpenRef,\n readOnly = false,\n validatedSelection,\n value,\n}: HumanReviewTextOverlayEditorProps) {\n const initialValue =\n value.kind === GridCellKind.Number ? value.displayData : value.data\n const [entryValue, setEntryValue] = React.useState(initialValue)\n const latestValueRef = React.useRef(initialValue)\n const finishedRef = React.useRef(false)\n\n const finishEditing = React.useCallback(\n (\n shouldSave: boolean,\n movement: readonly [-1 | 0 | 1, -1 | 0 | 1] = [0, 0]\n ) => {\n if (finishedRef.current) return\n\n finishedRef.current = true\n overlayOpenRef.current = false\n\n if (!shouldSave || readOnly) {\n onFinishedEditing(undefined, movement)\n return\n }\n\n if (value.kind === GridCellKind.Number) {\n const numericValue = Number(latestValueRef.current)\n\n onFinishedEditing(\n {\n ...value,\n data: Number.isFinite(numericValue) ? numericValue : value.data,\n displayData: latestValueRef.current,\n },\n movement\n )\n return\n }\n\n onFinishedEditing(\n {\n ...value,\n data: latestValueRef.current,\n displayData: latestValueRef.current,\n },\n movement\n )\n },\n [onFinishedEditing, overlayOpenRef, readOnly, value]\n )\n\n const handleEntryChange = React.useCallback(\n (event: React.ChangeEvent<HTMLTextAreaElement>) => {\n event.stopPropagation()\n latestValueRef.current = event.target.value\n setEntryValue(event.target.value)\n },\n []\n )\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n event.stopPropagation()\n\n if (event.key === "Escape") {\n event.preventDefault()\n finishEditing(false)\n return\n }\n\n if (event.key === "Tab") {\n event.preventDefault()\n finishEditing(true, [event.shiftKey ? -1 : 1, 0])\n return\n }\n\n if (event.key === "Enter" && !event.shiftKey) {\n event.preventDefault()\n finishEditing(true, [0, 1])\n }\n },\n [finishEditing]\n )\n\n React.useEffect(() => {\n overlayOpenRef.current = true\n\n return () => {\n overlayOpenRef.current = false\n }\n }, [overlayOpenRef])\n\n React.useEffect(() => {\n const handlePointerOutside = (event: PointerEvent | MouseEvent) => {\n const input = document.querySelector<HTMLTextAreaElement>(".gdg-input")\n const overlayRoot = input?.closest(".gdg-clip-region")\n\n if (!overlayRoot || overlayRoot.contains(event.target as Node | null)) {\n return\n }\n\n finishEditing(true)\n }\n\n document.addEventListener("pointerdown", handlePointerOutside, true)\n document.addEventListener("contextmenu", handlePointerOutside, true)\n\n return () => {\n document.removeEventListener("pointerdown", handlePointerOutside, true)\n document.removeEventListener("contextmenu", handlePointerOutside, true)\n }\n }, [finishEditing])\n\n return (\n <TextCellEntry\n autoFocus={!readOnly}\n disabled={readOnly}\n highlight={isHighlighted}\n value={entryValue}\n validatedSelection={validatedSelection}\n altNewline\n onChange={handleEntryChange}\n onKeyDown={handleKeyDown}\n />\n )\n}\n\nfunction getFieldIcon(type: SchemaPropertyType) {\n if (type === "number" || type === "integer") return InputNumericIcon\n if (type === "boolean") return TextCheckIcon\n if (type === "array") return SecondBracketIcon\n if (type === "object") return SourceCodeSquareIcon\n return InputTextIcon\n}\n\nfunction HumanReviewValueInput({\n readOnly = false,\n schema,\n value,\n onChange,\n}: {\n readOnly?: boolean\n schema: ReviewFieldSchema\n value: JsonPrimitive\n onChange: (value: JsonPrimitive) => void\n}) {\n if (schema.enum?.length) {\n return (\n <span className="relative inline-flex w-full rounded-lg border border-input bg-background text-sm text-foreground shadow-xs/5 dark:bg-input/32">\n <select\n disabled={readOnly}\n value={value === null ? "" : String(value)}\n onChange={(event) => onChange(event.target.value)}\n className="h-8.5 w-full appearance-none rounded-[inherit] bg-transparent px-3 text-sm outline-none sm:h-7.5"\n >\n {schema.enum.map((option) => (\n <option key={String(option)} value={String(option)}>\n {String(option)}\n </option>\n ))}\n </select>\n </span>\n )\n }\n\n if (schema.type === "number" || schema.type === "integer") {\n return (\n <Input\n nativeInput\n readOnly={readOnly}\n type="number"\n value={value === null ? "" : String(value)}\n onChange={(event) => {\n const nextValue = event.currentTarget.value\n onChange(nextValue === "" ? null : Number(nextValue))\n }}\n />\n )\n }\n\n if (schema.type === "boolean") {\n return (\n <div className="grid grid-cols-2 gap-1 rounded-lg bg-muted p-0.5">\n {[true, false].map((option) => (\n <Button\n key={String(option)}\n type="button"\n size="sm"\n variant={value === option ? "outline" : "ghost"}\n className={cn(\n "h-7 shadow-none",\n value === option && "bg-background dark:bg-input"\n )}\n disabled={readOnly}\n onClick={() => onChange(option)}\n >\n {option ? "True" : "False"}\n </Button>\n ))}\n </div>\n )\n }\n\n return (\n <Input\n nativeInput\n readOnly={readOnly}\n value={value === null ? "" : String(value)}\n onChange={(event) => onChange(event.currentTarget.value)}\n />\n )\n}\n\nfunction getArrayItemSchema(schema: ReviewFieldSchema): ReviewFieldSchema {\n return schema.items ?? { type: "string" }\n}\n\nfunction isComplexSchema(schema: ReviewFieldSchema) {\n return schema.type === "object" || schema.type === "array"\n}\n\nfunction summarizeComplexValue(value: JsonValue) {\n if (isJsonArray(value)) return `${value.length} items`\n if (isJsonObject(value)) return `${Object.keys(value).length} fields`\n return formatValue(value)\n}\n\nfunction getCellValueForArrayColumn(\n rowValue: JsonValue,\n itemSchema: ReviewFieldSchema,\n columnId: string\n) {\n if (itemSchema.type === "object") {\n return getObjectValue(rowValue, columnId)\n }\n\n return rowValue\n}\n\nfunction getCellSchemaForArrayColumn(\n itemSchema: ReviewFieldSchema,\n columnId: string\n) {\n if (itemSchema.type === "object") {\n return itemSchema.properties?.[columnId] ?? { type: "string" }\n }\n\n return itemSchema\n}\n\nfunction applyPrimitiveEdit(\n schema: ReviewFieldSchema,\n value: EditableGridCell\n): JsonValue | undefined {\n if (schema.type === "boolean" && value.kind === GridCellKind.Boolean) {\n return value.data\n }\n\n if (\n (schema.type === "number" || schema.type === "integer") &&\n value.kind === GridCellKind.Number\n ) {\n return value.data ?? null\n }\n\n if (value.kind === GridCellKind.Text) {\n if (schema.type === "number" || schema.type === "integer") {\n return value.data.trim() === "" ? null : Number(value.data)\n }\n\n return value.data\n }\n\n return undefined\n}\n\ntype ArrayNestedView = {\n rowIndex: number\n columnId: string\n title: string\n schema: ReviewFieldSchema\n value: JsonValue\n}\n\ntype ArrayReviewSide = "actual" | "expected"\n\ntype SyncedArrayNestedView = {\n activeSide: ArrayReviewSide | null\n stack: ArrayNestedView[]\n}\n\ntype SyncedArraySelection = {\n activeSide: ArrayReviewSide | null\n depth: number\n gridSelection: GridSelection\n}\n\nexport type HumanReviewTheme = "light" | "dark"\n\nconst EMPTY_SYNCED_ARRAY_NESTED_VIEW: SyncedArrayNestedView = {\n activeSide: null,\n stack: [],\n}\n\nconst EMPTY_SYNCED_ARRAY_SELECTION: SyncedArraySelection = {\n activeSide: null,\n depth: 0,\n gridSelection: emptyGridSelection,\n}\n\nfunction setNestedArrayValue({\n value,\n schema,\n nestedStack,\n nextNestedValue,\n}: {\n value: JsonValue\n schema: ReviewFieldSchema\n nestedStack: ArrayNestedView[]\n nextNestedValue: JsonValue\n}): JsonValue {\n const [currentView, ...remainingViews] = nestedStack\n\n if (!currentView) return nextNestedValue\n\n const itemSchema = getArrayItemSchema(schema)\n const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n const cellSchema = getCellSchemaForArrayColumn(\n itemSchema,\n currentView.columnId\n )\n const currentCellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n currentView.columnId\n )\n const nextCellValue: JsonValue = remainingViews.length\n ? setNestedArrayValue({\n value: currentCellValue,\n schema: cellSchema,\n nestedStack: remainingViews,\n nextNestedValue,\n })\n : nextNestedValue\n const nextRowValue: JsonValue =\n itemSchema.type === "object"\n ? setObjectValue(rowValue, currentView.columnId, nextCellValue)\n : nextCellValue\n\n return setArrayItemValue(value, currentView.rowIndex, nextRowValue)\n}\n\nfunction getNestedArrayValue({\n value,\n schema,\n nestedStack,\n}: {\n value: JsonValue\n schema: ReviewFieldSchema\n nestedStack: ArrayNestedView[]\n}): JsonValue {\n const [currentView, ...remainingViews] = nestedStack\n\n if (!currentView) return value\n\n const itemSchema = getArrayItemSchema(schema)\n const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n const cellSchema = getCellSchemaForArrayColumn(\n itemSchema,\n currentView.columnId\n )\n const cellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n currentView.columnId\n )\n\n if (!remainingViews.length) return cellValue\n\n return getNestedArrayValue({\n value: cellValue,\n schema: cellSchema,\n nestedStack: remainingViews,\n })\n}\n\nfunction HumanReviewArrayValueGrid({\n activeNestedSide = null,\n activeSelectionSide = null,\n label,\n nestedStackBaseDepth = 0,\n readOnly = false,\n schema,\n selectionDepth = 0,\n sharedGridSelection,\n sharedNestedStack,\n value,\n viewSide = "expected",\n metadataPath,\n onChange,\n onGridSelectionChange,\n onLocationHover,\n onNestedStackChange,\n resolveArrayItemMetadataPath,\n resolveLocation,\n}: {\n activeNestedSide?: ArrayReviewSide | null\n activeSelectionSide?: ArrayReviewSide | null\n label: string\n nestedStackBaseDepth?: number\n readOnly?: boolean\n schema: ReviewFieldSchema\n selectionDepth?: number\n sharedGridSelection?: GridSelection\n sharedNestedStack?: ArrayNestedView[]\n value: JsonValue\n viewSide?: ArrayReviewSide\n metadataPath?: string\n onChange?: (value: JsonValue) => void\n onGridSelectionChange?: (\n selection: GridSelection,\n side: ArrayReviewSide,\n depth: number\n ) => void\n onNestedStackChange?: (\n stack: ArrayNestedView[],\n side: ArrayReviewSide\n ) => void\n onLocationHover?: (location?: ReviewLocation) => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n}) {\n const rows = getArrayValue(value)\n const itemSchema = getArrayItemSchema(schema)\n const gridTheme = useHumanReviewGridTheme()\n const isDark = useIsDarkTheme()\n const [localNestedStack, setLocalNestedStack] = React.useState<\n ArrayNestedView[]\n >([])\n const [localGridSelection, setLocalGridSelection] =\n React.useState<GridSelection>(emptyGridSelection)\n const fastTextOverlayOpenRef = React.useRef(false)\n const nestedStack = sharedNestedStack ?? localNestedStack\n const visibleNestedStack = nestedStack.slice(nestedStackBaseDepth)\n const activeNestedView = visibleNestedStack[0] ?? null\n const activeNestedValue = activeNestedView\n ? getNestedArrayValue({\n value,\n schema,\n nestedStack: [activeNestedView],\n })\n : null\n const isActiveNestedSource =\n Boolean(activeNestedView) && activeNestedSide === viewSide\n const isMirroredNestedTarget =\n Boolean(activeNestedView) &&\n activeNestedSide !== null &&\n activeNestedSide !== viewSide\n const blueCellText = isDark ? "rgb(147, 197, 253)" : "rgb(37, 99, 235)"\n const selectedCellBackground = isDark\n ? "rgba(37, 99, 235, 0.2)"\n : "rgba(219, 234, 254, 0.85)"\n const mirroredCellBackground = isDark\n ? "rgba(167, 139, 250, 0.18)"\n : "rgba(237, 233, 254, 0.9)"\n const mirroredHighlightRegions = React.useMemo<\n React.ComponentProps<typeof DataEditor>["highlightRegions"]\n >(() => {\n if (\n !activeSelectionSide ||\n activeSelectionSide === viewSide ||\n selectionDepth !== nestedStackBaseDepth\n ) {\n return undefined\n }\n\n const ranges = getGridSelectionRanges(sharedGridSelection)\n if (!ranges.length) return undefined\n\n return ranges.map((range) => ({\n color: mirroredCellBackground,\n range,\n style: "dashed" as const,\n }))\n }, [\n activeSelectionSide,\n mirroredCellBackground,\n nestedStackBaseDepth,\n selectionDepth,\n sharedGridSelection,\n viewSide,\n ])\n\n const setNestedStack = React.useCallback(\n (\n updater:\n | ArrayNestedView[]\n | ((current: ArrayNestedView[]) => ArrayNestedView[])\n ) => {\n if (onNestedStackChange) {\n const nextStack =\n typeof updater === "function" ? updater(nestedStack) : updater\n\n onNestedStackChange(nextStack, viewSide)\n return\n }\n\n setLocalNestedStack(updater)\n },\n [nestedStack, onNestedStackChange, viewSide]\n )\n\n const handleGridSelectionChange = React.useCallback(\n (selection: GridSelection) => {\n flushSync(() => {\n setLocalGridSelection((current) =>\n areGridSelectionsEqual(current, selection) ? current : selection\n )\n })\n\n if (onGridSelectionChange) {\n if (\n activeSelectionSide === viewSide &&\n sharedGridSelection &&\n areGridSelectionsEqual(sharedGridSelection, selection)\n ) {\n return\n }\n\n React.startTransition(() => {\n onGridSelectionChange(selection, viewSide, nestedStackBaseDepth)\n })\n return\n }\n },\n [\n activeSelectionSide,\n nestedStackBaseDepth,\n onGridSelectionChange,\n sharedGridSelection,\n viewSide,\n ]\n )\n\n const columns = React.useMemo<GridColumn[]>(() => {\n if (itemSchema.type === "object") {\n const propertyEntries = Object.entries(itemSchema.properties ?? {})\n\n if (propertyEntries.length) {\n return propertyEntries.map(([key, propertySchema]) => ({\n id: key,\n title: propertySchema.title ?? key,\n width: isComplexSchema(propertySchema) ? 148 : 132,\n }))\n }\n }\n\n return [\n {\n id: "value",\n title: itemSchema.title ?? "Value",\n width: isComplexSchema(itemSchema) ? 148 : 180,\n },\n ]\n }, [itemSchema])\n\n const getCellContent = React.useCallback(\n ([col, row]: Item): GridCell => {\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n const cellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n columnId\n )\n const matchedNestedCell =\n activeNestedView?.rowIndex === row &&\n activeNestedView.columnId === columnId\n const nestedCellTheme: Partial<Theme> | undefined = matchedNestedCell\n ? {\n bgCell: isMirroredNestedTarget\n ? mirroredCellBackground\n : selectedCellBackground,\n textDark: blueCellText,\n }\n : undefined\n\n if (isComplexSchema(cellSchema)) {\n return {\n kind: GridCellKind.Text,\n data: summarizeComplexValue(cellValue),\n displayData: summarizeComplexValue(cellValue),\n allowOverlay: false,\n readonly: true,\n cursor: "pointer",\n activationBehaviorOverride: "double-click",\n themeOverride: {\n textDark: blueCellText,\n ...(nestedCellTheme ?? {}),\n },\n }\n }\n\n if (cellSchema.type === "boolean") {\n return {\n kind: GridCellKind.Boolean,\n data: typeof cellValue === "boolean" ? cellValue : false,\n allowOverlay: false,\n readonly: readOnly,\n }\n }\n\n if (cellSchema.type === "number" || cellSchema.type === "integer") {\n return {\n kind: GridCellKind.Number,\n data: typeof cellValue === "number" ? cellValue : undefined,\n displayData: typeof cellValue === "number" ? String(cellValue) : "",\n allowOverlay: true,\n readonly: false,\n }\n }\n\n return {\n kind: GridCellKind.Text,\n data:\n cellValue === null ||\n isJsonObject(cellValue) ||\n isJsonArray(cellValue)\n ? ""\n : String(cellValue),\n displayData:\n cellValue === null ||\n isJsonObject(cellValue) ||\n isJsonArray(cellValue)\n ? ""\n : String(cellValue),\n allowOverlay: true,\n readonly: false,\n }\n },\n [\n activeNestedView,\n blueCellText,\n columns,\n isMirroredNestedTarget,\n itemSchema,\n mirroredCellBackground,\n readOnly,\n rows,\n selectedCellBackground,\n ]\n )\n\n const updateCellValue = React.useCallback(\n ([col, row]: Item, nextCell: EditableGridCell) => {\n if (readOnly || !onChange) return\n\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n const nextValue = applyPrimitiveEdit(cellSchema, nextCell)\n\n if (nextValue === undefined) return\n\n const nextRowValue =\n itemSchema.type === "object"\n ? setObjectValue(rowValue, columnId, nextValue)\n : nextValue\n\n onChange(setArrayItemValue(value, row, nextRowValue))\n },\n [columns, itemSchema, onChange, readOnly, rows, value]\n )\n const provideEditor = React.useCallback<\n NonNullable<React.ComponentProps<typeof DataEditor>["provideEditor"]>\n >(\n (cell) => {\n if (\n cell.kind !== GridCellKind.Text &&\n cell.kind !== GridCellKind.Number\n ) {\n return undefined\n }\n\n return {\n editor: (props) => {\n if (\n props.value.kind !== GridCellKind.Text &&\n props.value.kind !== GridCellKind.Number\n ) {\n return null\n }\n\n return (\n <HumanReviewTextOverlayEditor\n {...(props as React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n >)}\n overlayOpenRef={fastTextOverlayOpenRef}\n readOnly={readOnly}\n />\n )\n },\n }\n },\n [readOnly]\n )\n const handleOutsideClick = React.useCallback(\n () => !fastTextOverlayOpenRef.current,\n []\n )\n const handleItemHovered = React.useCallback(\n (args: GridMouseEventArgs) => {\n if (!onLocationHover || !resolveLocation || !metadataPath) return\n\n if (args.kind !== "cell") {\n onLocationHover(undefined)\n return\n }\n\n const [col, row] = args.location\n const column = columns[col]\n const rowValue = rows[row]\n if (!column || rowValue === undefined) {\n onLocationHover(undefined)\n return\n }\n\n const columnId = String(column.id ?? "value")\n const rowMetadataPath = resolveArrayItemMetadataPath\n ? resolveArrayItemMetadataPath(metadataPath, row, rowValue)\n : `${metadataPath}[${row}]`\n if (!rowMetadataPath) {\n onLocationHover(undefined)\n return\n }\n\n const propertyMetadataPath =\n itemSchema.type === "object"\n ? `${rowMetadataPath}.${columnId}`\n : rowMetadataPath\n\n onLocationHover(\n resolveLocation(propertyMetadataPath) ??\n resolveLocation(rowMetadataPath)\n )\n },\n [\n columns,\n itemSchema.type,\n metadataPath,\n onLocationHover,\n resolveArrayItemMetadataPath,\n resolveLocation,\n rows,\n ]\n )\n\n const openNestedCell = React.useCallback(\n ([col, row]: Item) => {\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n\n if (!isComplexSchema(cellSchema)) return\n\n setNestedStack((current) => {\n const nextView = {\n rowIndex: row,\n columnId,\n title: `${column?.title ?? columnId} / row ${row + 1}`,\n schema: cellSchema,\n value: getCellValueForArrayColumn(rowValue, itemSchema, columnId),\n }\n const currentView = current[nestedStackBaseDepth]\n\n if (\n currentView?.rowIndex === nextView.rowIndex &&\n currentView.columnId === nextView.columnId\n ) {\n return current\n }\n\n return [...current.slice(0, nestedStackBaseDepth), nextView]\n })\n },\n [columns, itemSchema, nestedStackBaseDepth, rows, setNestedStack]\n )\n\n const updateNestedValue = React.useCallback(\n (nextNestedValue: JsonValue) => {\n if (!activeNestedView || readOnly || !onChange) return\n\n onChange(\n setNestedArrayValue({\n value,\n schema,\n nestedStack: visibleNestedStack.slice(0, 1),\n nextNestedValue,\n })\n )\n setNestedStack((current) =>\n current.map((view, index) =>\n index === nestedStackBaseDepth\n ? { ...view, value: nextNestedValue }\n : view\n )\n )\n },\n [\n activeNestedView,\n nestedStackBaseDepth,\n onChange,\n readOnly,\n schema,\n setNestedStack,\n value,\n visibleNestedStack,\n ]\n )\n\n return (\n <div\n onMouseLeave={() => onLocationHover?.(undefined)}\n className={cn(\n "relative overflow-hidden rounded-md border bg-background transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:shadow-[0_0_0_1px_rgb(59_130_246_/_8%)] hover:border-blue-500/50",\n isActiveNestedSource &&\n "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_10%)]"\n )}\n >\n <div>\n <div className="flex h-8 items-center justify-between gap-2 border-b px-2 text-[11px] font-medium text-muted-foreground">\n <span>{label}</span>\n <span>{rows.length} rows</span>\n </div>\n <div className="h-[220px]">\n <DataEditor\n columns={columns}\n rows={rows.length}\n getCellContent={getCellContent}\n cellActivationBehavior="double-click"\n gridSelection={localGridSelection}\n highlightRegions={mirroredHighlightRegions}\n onCellEdited={updateCellValue}\n onCellActivated={openNestedCell}\n onGridSelectionChange={handleGridSelectionChange}\n onItemHovered={handleItemHovered}\n provideEditor={provideEditor}\n isOutsideClick={handleOutsideClick}\n rowMarkers="number"\n smoothScrollX\n smoothScrollY\n theme={gridTheme}\n width="100%"\n height="100%"\n rowHeight={32}\n headerHeight={34}\n />\n </div>\n </div>\n {activeNestedView ? (\n <div className="absolute inset-0 z-10 flex flex-col bg-background">\n <div className="flex h-8 items-center gap-2 border-b px-2">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="size-6 text-muted-foreground"\n onClick={() =>\n setNestedStack((current) =>\n current.slice(\n 0,\n Math.max(nestedStackBaseDepth, current.length - 1)\n )\n )\n }\n aria-label="Back to parent array"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />\n </Button>\n <div className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">\n {activeNestedView.title}\n </div>\n </div>\n <div className="min-h-0 flex-1 overflow-auto p-2">\n {activeNestedView.schema.type === "array" ? (\n <HumanReviewArrayValueGrid\n label={\n activeNestedView.schema.title ?? activeNestedView.columnId\n }\n nestedStackBaseDepth={nestedStackBaseDepth + 1}\n readOnly={readOnly}\n schema={activeNestedView.schema}\n sharedGridSelection={sharedGridSelection}\n sharedNestedStack={sharedNestedStack}\n value={activeNestedValue}\n viewSide={viewSide}\n activeNestedSide={activeNestedSide}\n activeSelectionSide={activeSelectionSide}\n selectionDepth={selectionDepth}\n onChange={updateNestedValue}\n onGridSelectionChange={onGridSelectionChange}\n onNestedStackChange={onNestedStackChange}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n ) : (\n <HumanReviewObjectValueEditor\n schema={activeNestedView.schema}\n value={activeNestedValue}\n originalValue={activeNestedValue}\n readOnly={readOnly}\n onChange={updateNestedValue}\n />\n )}\n </div>\n </div>\n ) : null}\n </div>\n )\n}\n\nfunction HumanReviewObjectValueEditor({\n schema,\n value,\n originalValue,\n readOnly = false,\n onChange,\n}: {\n schema: ReviewFieldSchema\n value: JsonValue\n originalValue: JsonValue\n readOnly?: boolean\n onChange: (value: JsonValue) => void\n}) {\n const propertyEntries = Object.entries(schema.properties ?? {})\n\n if (!propertyEntries.length) {\n return (\n <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n No properties\n </div>\n )\n }\n\n return (\n <div className="space-y-2">\n {propertyEntries.map(([propertyKey, propertySchema]) => (\n <HumanReviewFieldCard\n key={propertyKey}\n field={{\n key: propertyKey,\n schema: propertySchema,\n actual: getObjectValue(originalValue, propertyKey),\n expected: getObjectValue(originalValue, propertyKey),\n }}\n value={getObjectValue(value, propertyKey)}\n originalValue={getObjectValue(originalValue, propertyKey)}\n readOnly={readOnly}\n onChange={(childValue) =>\n !readOnly &&\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onUndo={() =>\n !readOnly &&\n onChange(\n setObjectValue(\n value,\n propertyKey,\n getObjectValue(originalValue, propertyKey)\n )\n )\n }\n onSetNull={() =>\n !readOnly && onChange(setObjectValue(value, propertyKey, null))\n }\n />\n ))}\n </div>\n )\n}\n\ntype HumanReviewFieldCardProps = {\n field: ReviewField\n value: JsonValue\n originalValue: JsonValue\n active?: boolean\n activeFieldKey?: string\n readOnly?: boolean\n onChange: (value: JsonValue) => void\n onFieldFocus?: (field: ReviewField) => void\n onLocationHover?: (location?: ReviewLocation) => void\n onUndo: () => void\n onSetNull: () => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n}\n\nfunction areHumanReviewFieldCardPropsEqual(\n previous: HumanReviewFieldCardProps,\n next: HumanReviewFieldCardProps\n) {\n return (\n previous.field === next.field &&\n Object.is(previous.value, next.value) &&\n Object.is(previous.originalValue, next.originalValue) &&\n previous.active === next.active &&\n previous.activeFieldKey === next.activeFieldKey &&\n previous.readOnly === next.readOnly &&\n previous.onFieldFocus === next.onFieldFocus &&\n previous.onLocationHover === next.onLocationHover &&\n previous.resolveArrayItemMetadataPath ===\n next.resolveArrayItemMetadataPath &&\n previous.resolveLocation === next.resolveLocation\n )\n}\n\nconst HumanReviewFieldCard = React.memo(\n HumanReviewFieldCardBase,\n areHumanReviewFieldCardPropsEqual\n)\n\nfunction HumanReviewFieldCardBase({\n field,\n value,\n originalValue,\n active,\n activeFieldKey,\n readOnly = false,\n onChange,\n onFieldFocus,\n onLocationHover,\n onUndo,\n onSetNull,\n resolveArrayItemMetadataPath,\n resolveLocation,\n}: HumanReviewFieldCardProps) {\n const modified = !jsonValuesEqual(value, originalValue)\n const Icon = getFieldIcon(field.schema.type)\n const propertyEntries = Object.entries(field.schema.properties ?? {})\n const [syncedArrayNestedView, setSyncedArrayNestedView] =\n React.useState<SyncedArrayNestedView>(EMPTY_SYNCED_ARRAY_NESTED_VIEW)\n const [syncedArraySelection, setSyncedArraySelection] =\n React.useState<SyncedArraySelection>(EMPTY_SYNCED_ARRAY_SELECTION)\n const updateSyncedArrayNestedView = React.useCallback(\n (stack: ArrayNestedView[], side: ArrayReviewSide) => {\n const activeSide = stack.length ? side : null\n\n setSyncedArrayNestedView((current) =>\n current.activeSide === activeSide &&\n areArrayNestedViewsEqual(current.stack, stack)\n ? current\n : {\n activeSide,\n stack,\n }\n )\n },\n []\n )\n const updateSyncedArraySelection = React.useCallback(\n (gridSelection: GridSelection, side: ArrayReviewSide, depth: number) => {\n const activeSide = gridSelection.current ? side : null\n\n setSyncedArraySelection((current) =>\n current.activeSide === activeSide &&\n current.depth === depth &&\n areGridSelectionsEqual(current.gridSelection, gridSelection)\n ? current\n : {\n activeSide,\n depth,\n gridSelection,\n }\n )\n },\n []\n )\n const focusAndHoverField = React.useCallback(() => {\n onFieldFocus?.(field)\n onLocationHover?.(getReviewFieldLocation(field, resolveLocation))\n }, [field, onFieldFocus, onLocationHover, resolveLocation])\n\n return (\n <div\n tabIndex={0}\n onFocusCapture={focusAndHoverField}\n onMouseEnter={focusAndHoverField}\n onMouseLeave={() => onLocationHover?.(undefined)}\n className={cn(\n "rounded-lg border bg-background p-3 transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:bg-blue-500/5 hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",\n active &&\n "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_8%)]"\n )}\n >\n <div className="mb-3 flex min-h-8 items-start justify-between gap-3">\n <div className="min-w-0">\n <div className="flex min-w-0 items-center gap-2">\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">\n {field.schema.title ?? field.key}\n </div>\n </div>\n <span\n className={cn(\n "size-2 shrink-0 rounded-full bg-amber-400 transition-opacity",\n !modified && "opacity-0"\n )}\n />\n </div>\n <div className="truncate text-xs text-muted-foreground">\n {field.key}\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-1">\n {!readOnly && modified ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="text-muted-foreground"\n onClick={onUndo}\n aria-label={`Undo ${field.key}`}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Revert changes</TooltipContent>\n </Tooltip>\n ) : null}\n {!readOnly ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="text-muted-foreground"\n onClick={onSetNull}\n aria-label={`Set ${field.key} to null`}\n >\n <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Set to NULL</TooltipContent>\n </Tooltip>\n ) : null}\n <div className="flex h-6 items-center gap-1 rounded-md border bg-muted/50 px-1.5 text-xs text-muted-foreground">\n <HugeiconsIcon icon={Icon} className="size-3.5" />\n {field.schema.type}\n </div>\n </div>\n </div>\n {field.schema.type === "object" ? (\n <div className="rounded-md border bg-muted/25 p-2">\n <div className="mb-2 flex items-center justify-between gap-3 text-[11px] font-medium text-muted-foreground">\n <span>Properties</span>\n <span>{propertyEntries.length} fields</span>\n </div>\n <div className="space-y-2">\n {propertyEntries.length ? (\n propertyEntries.map(([propertyKey, schema]) => {\n const childField: ReviewField = {\n key: `${field.key}.${propertyKey}`,\n schema,\n actual: getObjectValue(field.actual, propertyKey),\n expected: getObjectValue(originalValue, propertyKey),\n metadataPath: `${field.metadataPath ?? field.key}.${propertyKey}`,\n }\n\n return (\n <HumanReviewFieldCard\n key={childField.key}\n field={childField}\n value={getObjectValue(value, propertyKey)}\n originalValue={childField.expected}\n active={childField.key === activeFieldKey}\n activeFieldKey={activeFieldKey}\n readOnly={readOnly}\n onChange={(childValue) =>\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onFieldFocus={onFieldFocus}\n onLocationHover={onLocationHover}\n onUndo={() =>\n onChange(\n setObjectValue(value, propertyKey, childField.expected)\n )\n }\n onSetNull={() =>\n onChange(setObjectValue(value, propertyKey, null))\n }\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n )\n })\n ) : (\n <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n No properties\n </div>\n )}\n </div>\n </div>\n ) : field.schema.type === "array" ? (\n <div className="grid gap-2">\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Actual"\n metadataPath={field.metadataPath ?? field.key}\n readOnly\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n schema={field.schema}\n selectionDepth={syncedArraySelection.depth}\n sharedGridSelection={syncedArraySelection.gridSelection}\n sharedNestedStack={syncedArrayNestedView.stack}\n value={field.actual}\n viewSide="actual"\n onGridSelectionChange={updateSyncedArraySelection}\n onLocationHover={onLocationHover}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Expected"\n metadataPath={field.metadataPath ?? field.key}\n readOnly={readOnly}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n schema={field.schema}\n selectionDepth={syncedArraySelection.depth}\n sharedGridSelection={syncedArraySelection.gridSelection}\n sharedNestedStack={syncedArrayNestedView.stack}\n value={value}\n viewSide="expected"\n onChange={onChange}\n onGridSelectionChange={updateSyncedArraySelection}\n onLocationHover={onLocationHover}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n </div>\n ) : (\n <div className="grid gap-2 sm:grid-cols-2">\n <div className="rounded-md border bg-muted/30 p-2">\n {field.schema.description ? (\n <p className="mb-2 text-xs text-muted-foreground">\n {field.schema.description}\n </p>\n ) : null}\n <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n Actual\n </div>\n <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">\n {formatValue(field.actual)}\n </div>\n </div>\n <div className="rounded-md border bg-muted/30 p-2">\n <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n Expected\n </div>\n <HumanReviewValueInput\n readOnly={readOnly}\n schema={field.schema}\n value={getPrimitiveValue(value)}\n onChange={onChange}\n />\n </div>\n </div>\n )}\n </div>\n )\n}\n\nexport function HumanReviewHighlight({\n location,\n}: {\n location: ReviewLocation\n}) {\n const area = location.area\n\n return (\n <div\n className={cn(\n "pointer-events-none absolute z-10 border",\n REVIEW_HIGHLIGHT_STYLE\n )}\n style={{\n left: `${area.left}%`,\n top: `${area.top}%`,\n width: `${area.width}%`,\n height: `${area.height}%`,\n }}\n />\n )\n}\n\nexport function JsonDiffView({\n actual,\n expected,\n theme = "light",\n}: {\n actual: JsonObject\n expected: JsonObject\n theme?: HumanReviewTheme\n}) {\n const oldFile = React.useMemo(\n () => ({\n name: "actual.json",\n contents: formatJson(actual),\n lang: "json",\n }),\n [actual]\n )\n const newFile = React.useMemo(\n () => ({\n name: "expected.json",\n contents: formatJson(expected),\n lang: "json",\n }),\n [expected]\n )\n\n return (\n <Virtualizer\n className="h-full overflow-auto rounded-b-xl bg-surface/60"\n contentClassName="min-w-full"\n >\n <div className="human-review-diff h-full text-xs">\n <MultiFileDiff\n className="block min-w-full"\n style={DIFF_VIEWER_THEME}\n oldFile={oldFile}\n newFile={newFile}\n options={{\n diffStyle: "split",\n disableFileHeader: true,\n diffIndicators: "bars",\n hunkSeparators: "line-info-basic",\n overflow: "wrap",\n themeType: theme,\n theme: {\n light: "pierre-light-soft",\n dark: "pierre-dark-soft",\n },\n }}\n />\n </div>\n </Virtualizer>\n )\n}\n\nexport function HumanReviewPanel({\n fields = REVIEW_FIELDS,\n activeFieldKey,\n className,\n onFieldFocus,\n onLocationHover,\n resolveArrayItemMetadataPath,\n resolveLocation,\n theme = "light",\n}: {\n fields?: ReviewField[]\n activeFieldKey?: string\n className?: string\n onFieldFocus?: (field: ReviewField) => void\n onLocationHover?: (location?: ReviewLocation) => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n theme?: HumanReviewTheme\n} = {}) {\n const [activeTab, setActiveTab] = React.useState("form")\n const actualValues = React.useMemo(\n () => valuesFromFields(fields, "actual"),\n [fields]\n )\n const initialExpectedValues = React.useMemo(\n () => valuesFromFields(fields, "expected"),\n [fields]\n )\n const [expected, setExpected] = React.useState<JsonObject>(\n initialExpectedValues\n )\n\n React.useEffect(() => {\n setExpected(initialExpectedValues)\n }, [initialExpectedValues])\n\n const updateValue = React.useCallback((key: string, value: JsonValue) => {\n setExpected((current) =>\n Object.is(current[key], value) ? current : { ...current, [key]: value }\n )\n }, [])\n\n return (\n <TooltipProvider delay={200}>\n <Tabs\n value={activeTab}\n onValueChange={setActiveTab}\n className={cn("flex h-[560px] flex-col gap-0 bg-background", className)}\n >\n <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">\n <TabsList className="h-8 sm:h-7">\n <TabsTrigger value="form" className="h-7 sm:h-6">\n <HugeiconsIcon icon={TextCheckIcon} className="size-4" />\n Form\n </TabsTrigger>\n <TabsTrigger value="json" className="h-7 sm:h-6">\n <HugeiconsIcon icon={SourceCodeSquareIcon} className="size-4" />\n JSON\n </TabsTrigger>\n </TabsList>\n </div>\n <TabsContent value="form" keepMounted className="min-h-0 flex-1">\n <ScrollArea className="h-full" scrollFade>\n <div className="space-y-3 p-3">\n {fields.map((field) => (\n <HumanReviewFieldCard\n key={field.key}\n field={field}\n value={expected[field.key] ?? null}\n originalValue={field.expected}\n active={\n field.key === activeFieldKey ||\n activeFieldKey?.startsWith(`${field.key}.`)\n }\n activeFieldKey={activeFieldKey}\n onChange={(value) => updateValue(field.key, value)}\n onFieldFocus={onFieldFocus}\n onLocationHover={onLocationHover}\n onUndo={() => updateValue(field.key, field.expected)}\n onSetNull={() => updateValue(field.key, null)}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n ))}\n </div>\n </ScrollArea>\n </TabsContent>\n <TabsContent value="json" keepMounted className="min-h-0 flex-1">\n <JsonDiffView\n actual={actualValues}\n expected={expected}\n theme={theme}\n />\n </TabsContent>\n </Tabs>\n </TooltipProvider>\n )\n}\n'
+ '"use client"\n\nimport * as React from "react"\nimport {\n DataEditor,\n emptyGridSelection,\n GridCellKind,\n TextCellEntry,\n type EditableGridCell,\n type GridCell,\n type GridColumn,\n type GridMouseEventArgs,\n type GridSelection,\n type Item,\n type NumberCell,\n type ProvideEditorComponent,\n type Rectangle,\n type TextCell,\n type Theme,\n} from "@glideapps/glide-data-grid"\nimport {\n ArrowLeft01Icon,\n CancelCircleIcon,\n InputNumericIcon,\n InputTextIcon,\n SecondBracketIcon,\n SourceCodeSquareIcon,\n TextCheckIcon,\n Undo02Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { MultiFileDiff, Virtualizer } from "@pierre/diffs/react"\nimport { flushSync } from "react-dom"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/registry/new-york-v4/ui/button"\nimport { Input } from "@/registry/new-york-v4/ui/input"\nimport { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"\nimport {\n Tabs,\n TabsContent,\n TabsList,\n TabsTrigger,\n} from "@/registry/new-york-v4/ui/tabs"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nimport "@glideapps/glide-data-grid/dist/index.css"\n\nexport type JsonPrimitive = string | number | boolean | null\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray\nexport type JsonObject = { [key: string]: JsonValue }\nexport type JsonArray = JsonValue[]\nexport type SchemaPropertyType =\n | "string"\n | "number"\n | "integer"\n | "boolean"\n | "object"\n | "array"\n\nexport type ReviewFieldSchema = {\n type: SchemaPropertyType\n title?: string\n description?: string\n enum?: Array<string | number>\n properties?: Record<string, ReviewFieldSchema>\n items?: ReviewFieldSchema\n}\n\nexport type HighlightArea = {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport type ReviewField = {\n key: string\n schema: ReviewFieldSchema\n actual: JsonValue\n expected: JsonValue\n location?: ReviewLocation\n metadataPath?: string\n}\n\nexport type ReviewLocation = {\n page: number\n area: HighlightArea\n}\n\nexport type ReviewCitation = {\n page: number\n polygon?: Array<{ x: number; y: number }>\n pageWidth: number\n pageHeight: number\n}\n\nexport type ReviewMetadataEntry = {\n citations?: ReviewCitation[]\n}\n\nconst DEFAULT_ZOOM = 0.75\nconst REVIEW_HIGHLIGHT_STYLE =\n "border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"\n\nfunction readIsDarkTheme() {\n return (\n typeof document !== "undefined" &&\n document.documentElement.classList.contains("dark")\n )\n}\n\n// A single shared MutationObserver backs every consumer. Each grid previously\n// created its own observer (two, via useHumanReviewGridTheme), so opening a\n// nested array view spun up and tore down several observers at once.\nconst darkThemeListeners = new Set<(isDark: boolean) => void>()\nlet darkThemeObserver: MutationObserver | null = null\nlet sharedIsDarkTheme = false\n\nfunction ensureDarkThemeObserver() {\n if (\n darkThemeObserver ||\n typeof document === "undefined" ||\n typeof MutationObserver === "undefined"\n ) {\n return\n }\n\n sharedIsDarkTheme = readIsDarkTheme()\n darkThemeObserver = new MutationObserver(() => {\n const nextIsDark = readIsDarkTheme()\n if (nextIsDark === sharedIsDarkTheme) return\n\n sharedIsDarkTheme = nextIsDark\n darkThemeListeners.forEach((listener) => listener(nextIsDark))\n })\n darkThemeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ["class"],\n })\n}\n\nfunction useIsDarkTheme() {\n const [isDark, setIsDark] = React.useState(readIsDarkTheme)\n\n React.useEffect(() => {\n ensureDarkThemeObserver()\n setIsDark(sharedIsDarkTheme)\n darkThemeListeners.add(setIsDark)\n\n return () => {\n darkThemeListeners.delete(setIsDark)\n if (darkThemeListeners.size === 0 && darkThemeObserver) {\n darkThemeObserver.disconnect()\n darkThemeObserver = null\n }\n }\n }, [])\n\n return isDark\n}\n\nfunction useHumanReviewGridTheme() {\n const isDark = useIsDarkTheme()\n\n return React.useMemo<Partial<Theme>>(\n () => ({\n accentColor: isDark ? "rgb(96, 165, 250)" : "rgb(37, 99, 235)",\n accentLight: isDark ? "rgba(29, 78, 216, 0.15)" : "rgb(219, 234, 254)",\n accentFg: "rgb(255, 255, 255)",\n textDark: isDark ? "rgb(229, 229, 229)" : "rgb(23, 23, 23)",\n textMedium: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n textLight: isDark ? "rgb(115, 115, 115)" : "rgb(163, 163, 163)",\n textBubble: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n textHeader: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n textGroupHeader: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n bgCell: isDark ? "rgb(10, 10, 10)" : "rgb(255, 255, 255)",\n bgCellMedium: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n bgHeader: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n bgHeaderHasFocus: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n bgHeaderHovered: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n borderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n horizontalBorderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n cellHorizontalPadding: 8,\n cellVerticalPadding: 3,\n headerIconSize: 18,\n baseFontStyle: "13px",\n headerFontStyle: "600 13px",\n markerFontStyle: "11px",\n fontFamily: \'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif\',\n editorFontSize: "13px",\n }),\n [isDark]\n )\n}\n\nexport const REVIEW_FIELDS: ReviewField[] = [\n {\n key: "statement_period",\n schema: {\n type: "string",\n title: "Statement period",\n description: "Date range covered by the bank statement.",\n },\n actual: "Jan 1-31, 2026",\n expected: "January 1-31, 2026",\n location: {\n page: 1,\n area: { left: 31, top: 30, width: 40, height: 5.8 },\n },\n },\n {\n key: "transactions",\n schema: {\n type: "array",\n title: "Transactions",\n description: "Posted account activity during the statement period.",\n items: {\n type: "object",\n properties: {\n date: {\n type: "string",\n title: "Date",\n },\n description: {\n type: "string",\n title: "Description",\n },\n amount: {\n type: "number",\n title: "Amount",\n },\n category: {\n type: "string",\n title: "Category",\n },\n merchant: {\n type: "object",\n title: "Merchant",\n properties: {\n name: {\n type: "string",\n title: "Name",\n },\n city: {\n type: "string",\n title: "City",\n },\n risk_level: {\n type: "string",\n title: "Risk level",\n },\n },\n },\n tags: {\n type: "array",\n title: "Tags",\n items: {\n type: "string",\n title: "Tag",\n },\n },\n },\n },\n },\n actual: [\n {\n date: "2026-01-03",\n description: "ACH CREDIT PAYROLL",\n amount: 4250,\n category: "Deposit",\n merchant: {\n name: "Acme Payroll",\n city: "New York",\n risk_level: "low",\n },\n tags: ["payroll", "recurring"],\n },\n {\n date: "2026-01-12",\n description: "POS PURCHASE GROCERY MART",\n amount: -86.42,\n category: "Debit",\n merchant: {\n name: "Grocery Mart",\n city: "Brooklyn",\n risk_level: "medium",\n },\n tags: ["card", "groceries"],\n },\n ],\n expected: [\n {\n date: "2026-01-03",\n description: "ACH CREDIT PAYROLL",\n amount: 4250,\n category: "Deposit",\n merchant: {\n name: "Acme Payroll",\n city: "New York",\n risk_level: "low",\n },\n tags: ["payroll", "recurring"],\n },\n {\n date: "2026-01-12",\n description: "POS PURCHASE GROCERY MART",\n amount: -68.42,\n category: "Debit",\n merchant: {\n name: "Grocery Mart",\n city: "Brooklyn",\n risk_level: "low",\n },\n tags: ["card", "groceries", "needs_review"],\n },\n ],\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "ending_balance",\n schema: {\n type: "number",\n title: "Ending balance",\n description: "Final account balance at the end of the statement period.",\n },\n actual: 12840.18,\n expected: 12858.18,\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "overdraft_protection_enabled",\n schema: {\n type: "boolean",\n title: "Overdraft protection enabled",\n description: "Whether overdraft protection is enabled for the account.",\n },\n actual: false,\n expected: true,\n location: {\n page: 2,\n area: { left: 9.5, top: 12, width: 81, height: 11.5 },\n },\n },\n {\n key: "account_details",\n schema: {\n type: "object",\n title: "Account details",\n description: "Account owner and identifying details from the statement.",\n properties: {\n holder_name: {\n type: "string",\n title: "Holder name",\n },\n account_last_four: {\n type: "string",\n title: "Account last four",\n },\n account_type: {\n type: "string",\n title: "Account type",\n },\n mailing_address: {\n type: "object",\n title: "Mailing address",\n properties: {\n line_1: {\n type: "string",\n title: "Line 1",\n },\n city: {\n type: "string",\n title: "City",\n },\n state: {\n type: "string",\n title: "State",\n },\n },\n },\n linked_accounts: {\n type: "array",\n title: "Linked accounts",\n items: {\n type: "object",\n properties: {\n nickname: {\n type: "string",\n title: "Nickname",\n },\n last_four: {\n type: "string",\n title: "Last four",\n },\n },\n },\n },\n },\n },\n actual: {\n holder_name: "Jordan Lee",\n account_last_four: "4821",\n account_type: "Checking",\n mailing_address: {\n line_1: "42 Market Street",\n city: "Brooklyn",\n state: "NY",\n },\n linked_accounts: [\n {\n nickname: "Operations reserve",\n last_four: "1842",\n },\n ],\n },\n expected: {\n holder_name: "Jordan Lee",\n account_last_four: "4821",\n account_type: "Premier Checking",\n mailing_address: {\n line_1: "42 Market Street",\n city: "New York",\n state: "NY",\n },\n linked_accounts: [\n {\n nickname: "Operations reserve",\n last_four: "1842",\n },\n {\n nickname: "Payroll sweep",\n last_four: "9174",\n },\n ],\n },\n },\n]\n\nfunction getCitationLocation(\n citation: ReviewCitation\n): ReviewLocation | undefined {\n const polygon = citation.polygon\n if (!polygon?.length || !citation.pageWidth || !citation.pageHeight) {\n return undefined\n }\n\n const xs = polygon.map((point) => point.x)\n const ys = polygon.map((point) => point.y)\n const left = Math.min(...xs)\n const top = Math.min(...ys)\n const right = Math.max(...xs)\n const bottom = Math.max(...ys)\n\n return {\n page: citation.page,\n area: {\n left: (left / citation.pageWidth) * 100,\n top: (top / citation.pageHeight) * 100,\n width: ((right - left) / citation.pageWidth) * 100,\n height: ((bottom - top) / citation.pageHeight) * 100,\n },\n }\n}\n\nexport function getMetadataLocation(\n metadata: Record<string, ReviewMetadataEntry> | undefined,\n metadataPath: string | undefined\n) {\n if (!metadata || !metadataPath) return undefined\n\n const citation = metadata[metadataPath]?.citations?.find(\n (candidate) => candidate.polygon?.length\n )\n\n return citation ? getCitationLocation(citation) : undefined\n}\n\nexport function getReviewFieldLocation(\n field: ReviewField | undefined,\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n) {\n if (!field) return undefined\n\n return (\n field.location ??\n resolveLocation?.(field.metadataPath ?? field.key) ??\n undefined\n )\n}\n\nexport function getReviewLocationKey(location: ReviewLocation | undefined) {\n if (!location) return null\n\n const { area } = location\n return [location.page, area.left, area.top, area.width, area.height].join(":")\n}\n\nfunction valuesFromFields(\n fields: ReviewField[],\n valueKey: "actual" | "expected"\n) {\n return fields.reduce<JsonObject>((values, field) => {\n values[field.key] = field[valueKey]\n return values\n }, {})\n}\n\nfunction formatJson(value: unknown) {\n return JSON.stringify(value, null, 2)\n}\n\nfunction isJsonObject(value: JsonValue): value is JsonObject {\n return typeof value === "object" && value !== null && !Array.isArray(value)\n}\n\nfunction isJsonArray(value: JsonValue): value is JsonArray {\n return Array.isArray(value)\n}\n\nfunction getObjectValue(value: JsonValue, key: string): JsonValue {\n if (!isJsonObject(value)) return null\n return value[key] ?? null\n}\n\nfunction setObjectValue(\n value: JsonValue,\n key: string,\n childValue: JsonValue\n): JsonObject {\n return {\n ...(isJsonObject(value) ? value : {}),\n [key]: childValue,\n }\n}\n\nfunction getArrayValue(value: JsonValue): JsonArray {\n return isJsonArray(value) ? value : []\n}\n\nfunction setArrayItemValue(\n value: JsonValue,\n index: number,\n childValue: JsonValue\n): JsonArray {\n const nextValue = getArrayValue(value).slice()\n nextValue[index] = childValue\n return nextValue\n}\n\nfunction getPrimitiveValue(value: JsonValue): JsonPrimitive {\n return isJsonObject(value) || isJsonArray(value) ? null : value\n}\n\nfunction jsonValuesEqual(left: JsonValue, right: JsonValue) {\n return formatJson(left) === formatJson(right)\n}\n\nexport function findReviewField(\n fields: ReviewField[],\n fieldKey: string | undefined\n): ReviewField | undefined {\n if (!fieldKey) return undefined\n\n for (const field of fields) {\n if (field.key === fieldKey) return field\n\n if (field.schema.type === "object") {\n const childFields = Object.entries(field.schema.properties ?? {}).map(\n ([key, schema]): ReviewField => ({\n key: `${field.key}.${key}`,\n schema,\n actual: getObjectValue(field.actual, key),\n expected: getObjectValue(field.expected, key),\n metadataPath: `${field.metadataPath ?? field.key}.${key}`,\n })\n )\n const childField = findReviewField(childFields, fieldKey)\n if (childField) return childField\n }\n }\n\n return undefined\n}\n\nfunction formatValue(value: JsonValue) {\n if (value === null) return "NULL"\n if (isJsonObject(value) || isJsonArray(value)) return formatJson(value)\n if (typeof value === "boolean") return value ? "true" : "false"\n return String(value)\n}\n\nfunction areGridRangesEqual(\n left: Readonly<Rectangle> | undefined,\n right: Readonly<Rectangle> | undefined\n) {\n return (\n left === right ||\n (left !== undefined &&\n right !== undefined &&\n left.x === right.x &&\n left.y === right.y &&\n left.width === right.width &&\n left.height === right.height)\n )\n}\n\nfunction areGridRangeStacksEqual(\n left: readonly Readonly<Rectangle>[] | undefined,\n right: readonly Readonly<Rectangle>[] | undefined\n) {\n if (left === right) return true\n if (!left || !right || left.length !== right.length) return false\n\n return left.every((range, index) => areGridRangesEqual(range, right[index]))\n}\n\nfunction areGridSelectionsEqual(left: GridSelection, right: GridSelection) {\n const leftCurrent = left.current\n const rightCurrent = right.current\n\n return (\n leftCurrent?.cell[0] === rightCurrent?.cell[0] &&\n leftCurrent?.cell[1] === rightCurrent?.cell[1] &&\n areGridRangesEqual(leftCurrent?.range, rightCurrent?.range) &&\n areGridRangeStacksEqual(\n leftCurrent?.rangeStack,\n rightCurrent?.rangeStack\n ) &&\n left.columns.equals(right.columns) &&\n left.rows.equals(right.rows)\n )\n}\n\nfunction getGridSelectionRanges(selection: GridSelection | undefined) {\n const current = selection?.current\n if (!current) return []\n\n return [...(current.rangeStack ?? []), current.range]\n}\n\nfunction areArrayNestedViewsEqual(\n left: ArrayNestedView[],\n right: ArrayNestedView[]\n) {\n if (left === right) return true\n if (left.length !== right.length) return false\n\n return left.every((view, index) => {\n const other = right[index]\n\n return (\n view.rowIndex === other?.rowIndex &&\n view.columnId === other.columnId &&\n view.title === other.title &&\n view.schema === other.schema &&\n Object.is(view.value, other.value)\n )\n })\n}\n\ntype HumanReviewOverlayCell = TextCell | NumberCell\n\ntype HumanReviewTextOverlayEditorProps = React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n> & {\n overlayOpenRef: React.RefObject<boolean>\n readOnly?: boolean\n}\n\nfunction HumanReviewTextOverlayEditor({\n isHighlighted,\n onFinishedEditing,\n overlayOpenRef,\n readOnly = false,\n validatedSelection,\n value,\n}: HumanReviewTextOverlayEditorProps) {\n const initialValue =\n value.kind === GridCellKind.Number ? value.displayData : value.data\n const [entryValue, setEntryValue] = React.useState(initialValue)\n const latestValueRef = React.useRef(initialValue)\n const finishedRef = React.useRef(false)\n\n const finishEditing = React.useCallback(\n (\n shouldSave: boolean,\n movement: readonly [-1 | 0 | 1, -1 | 0 | 1] = [0, 0]\n ) => {\n if (finishedRef.current) return\n\n finishedRef.current = true\n overlayOpenRef.current = false\n\n if (!shouldSave || readOnly) {\n onFinishedEditing(undefined, movement)\n return\n }\n\n if (value.kind === GridCellKind.Number) {\n const numericValue = Number(latestValueRef.current)\n\n onFinishedEditing(\n {\n ...value,\n data: Number.isFinite(numericValue) ? numericValue : value.data,\n displayData: latestValueRef.current,\n },\n movement\n )\n return\n }\n\n onFinishedEditing(\n {\n ...value,\n data: latestValueRef.current,\n displayData: latestValueRef.current,\n },\n movement\n )\n },\n [onFinishedEditing, overlayOpenRef, readOnly, value]\n )\n\n const handleEntryChange = React.useCallback(\n (event: React.ChangeEvent<HTMLTextAreaElement>) => {\n event.stopPropagation()\n latestValueRef.current = event.target.value\n setEntryValue(event.target.value)\n },\n []\n )\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n event.stopPropagation()\n\n if (event.key === "Escape") {\n event.preventDefault()\n finishEditing(false)\n return\n }\n\n if (event.key === "Tab") {\n event.preventDefault()\n finishEditing(true, [event.shiftKey ? -1 : 1, 0])\n return\n }\n\n if (event.key === "Enter" && !event.shiftKey) {\n event.preventDefault()\n finishEditing(true, [0, 1])\n }\n },\n [finishEditing]\n )\n\n React.useEffect(() => {\n overlayOpenRef.current = true\n\n return () => {\n overlayOpenRef.current = false\n }\n }, [overlayOpenRef])\n\n React.useEffect(() => {\n const handlePointerOutside = (event: PointerEvent | MouseEvent) => {\n const input = document.querySelector<HTMLTextAreaElement>(".gdg-input")\n const overlayRoot = input?.closest(".gdg-clip-region")\n\n if (!overlayRoot || overlayRoot.contains(event.target as Node | null)) {\n return\n }\n\n finishEditing(true)\n }\n\n document.addEventListener("pointerdown", handlePointerOutside, true)\n document.addEventListener("contextmenu", handlePointerOutside, true)\n\n return () => {\n document.removeEventListener("pointerdown", handlePointerOutside, true)\n document.removeEventListener("contextmenu", handlePointerOutside, true)\n }\n }, [finishEditing])\n\n return (\n <TextCellEntry\n autoFocus={!readOnly}\n disabled={readOnly}\n highlight={isHighlighted}\n value={entryValue}\n validatedSelection={validatedSelection}\n altNewline\n onChange={handleEntryChange}\n onKeyDown={handleKeyDown}\n />\n )\n}\n\nfunction getFieldIcon(type: SchemaPropertyType) {\n if (type === "number" || type === "integer") return InputNumericIcon\n if (type === "boolean") return TextCheckIcon\n if (type === "array") return SecondBracketIcon\n if (type === "object") return SourceCodeSquareIcon\n return InputTextIcon\n}\n\nfunction HumanReviewValueInput({\n readOnly = false,\n schema,\n value,\n onChange,\n}: {\n readOnly?: boolean\n schema: ReviewFieldSchema\n value: JsonPrimitive\n onChange: (value: JsonPrimitive) => void\n}) {\n if (schema.enum?.length) {\n return (\n <span className="relative inline-flex w-full rounded-lg border border-input bg-background text-sm text-foreground shadow-xs/5 dark:bg-input/32">\n <select\n disabled={readOnly}\n value={value === null ? "" : String(value)}\n onChange={(event) => onChange(event.target.value)}\n className="h-8.5 w-full appearance-none rounded-[inherit] bg-transparent px-3 text-sm outline-none sm:h-7.5"\n >\n {schema.enum.map((option) => (\n <option key={String(option)} value={String(option)}>\n {String(option)}\n </option>\n ))}\n </select>\n </span>\n )\n }\n\n if (schema.type === "number" || schema.type === "integer") {\n return (\n <Input\n nativeInput\n readOnly={readOnly}\n type="number"\n value={value === null ? "" : String(value)}\n onChange={(event) => {\n const nextValue = event.currentTarget.value\n onChange(nextValue === "" ? null : Number(nextValue))\n }}\n />\n )\n }\n\n if (schema.type === "boolean") {\n return (\n <div className="grid grid-cols-2 gap-1 rounded-lg bg-muted p-0.5">\n {[true, false].map((option) => (\n <Button\n key={String(option)}\n type="button"\n size="sm"\n variant={value === option ? "outline" : "ghost"}\n className={cn(\n "h-7 shadow-none",\n value === option && "bg-background dark:bg-input"\n )}\n disabled={readOnly}\n onClick={() => onChange(option)}\n >\n {option ? "True" : "False"}\n </Button>\n ))}\n </div>\n )\n }\n\n return (\n <Input\n nativeInput\n readOnly={readOnly}\n value={value === null ? "" : String(value)}\n onChange={(event) => onChange(event.currentTarget.value)}\n />\n )\n}\n\nfunction getArrayItemSchema(schema: ReviewFieldSchema): ReviewFieldSchema {\n return schema.items ?? { type: "string" }\n}\n\nfunction isComplexSchema(schema: ReviewFieldSchema) {\n return schema.type === "object" || schema.type === "array"\n}\n\nfunction summarizeComplexValue(value: JsonValue) {\n if (isJsonArray(value)) return `${value.length} items`\n if (isJsonObject(value)) return `${Object.keys(value).length} fields`\n return formatValue(value)\n}\n\nfunction getCellValueForArrayColumn(\n rowValue: JsonValue,\n itemSchema: ReviewFieldSchema,\n columnId: string\n) {\n if (itemSchema.type === "object") {\n return getObjectValue(rowValue, columnId)\n }\n\n return rowValue\n}\n\nfunction getCellSchemaForArrayColumn(\n itemSchema: ReviewFieldSchema,\n columnId: string\n) {\n if (itemSchema.type === "object") {\n return itemSchema.properties?.[columnId] ?? { type: "string" }\n }\n\n return itemSchema\n}\n\nfunction applyPrimitiveEdit(\n schema: ReviewFieldSchema,\n value: EditableGridCell\n): JsonValue | undefined {\n if (schema.type === "boolean" && value.kind === GridCellKind.Boolean) {\n return value.data\n }\n\n if (\n (schema.type === "number" || schema.type === "integer") &&\n value.kind === GridCellKind.Number\n ) {\n return value.data ?? null\n }\n\n if (value.kind === GridCellKind.Text) {\n if (schema.type === "number" || schema.type === "integer") {\n return value.data.trim() === "" ? null : Number(value.data)\n }\n\n return value.data\n }\n\n return undefined\n}\n\ntype ArrayNestedView = {\n rowIndex: number\n columnId: string\n title: string\n schema: ReviewFieldSchema\n value: JsonValue\n}\n\ntype ArrayReviewSide = "actual" | "expected"\n\ntype SyncedArrayNestedView = {\n activeSide: ArrayReviewSide | null\n stack: ArrayNestedView[]\n}\n\ntype SyncedArraySelection = {\n activeSide: ArrayReviewSide | null\n depth: number\n gridSelection: GridSelection\n}\n\nexport type HumanReviewTheme = "light" | "dark"\n\nconst EMPTY_SYNCED_ARRAY_NESTED_VIEW: SyncedArrayNestedView = {\n activeSide: null,\n stack: [],\n}\n\nconst EMPTY_SYNCED_ARRAY_SELECTION: SyncedArraySelection = {\n activeSide: null,\n depth: 0,\n gridSelection: emptyGridSelection,\n}\n\nfunction setNestedArrayValue({\n value,\n schema,\n nestedStack,\n nextNestedValue,\n}: {\n value: JsonValue\n schema: ReviewFieldSchema\n nestedStack: ArrayNestedView[]\n nextNestedValue: JsonValue\n}): JsonValue {\n const [currentView, ...remainingViews] = nestedStack\n\n if (!currentView) return nextNestedValue\n\n const itemSchema = getArrayItemSchema(schema)\n const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n const cellSchema = getCellSchemaForArrayColumn(\n itemSchema,\n currentView.columnId\n )\n const currentCellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n currentView.columnId\n )\n const nextCellValue: JsonValue = remainingViews.length\n ? setNestedArrayValue({\n value: currentCellValue,\n schema: cellSchema,\n nestedStack: remainingViews,\n nextNestedValue,\n })\n : nextNestedValue\n const nextRowValue: JsonValue =\n itemSchema.type === "object"\n ? setObjectValue(rowValue, currentView.columnId, nextCellValue)\n : nextCellValue\n\n return setArrayItemValue(value, currentView.rowIndex, nextRowValue)\n}\n\nfunction getNestedArrayValue({\n value,\n schema,\n nestedStack,\n}: {\n value: JsonValue\n schema: ReviewFieldSchema\n nestedStack: ArrayNestedView[]\n}): JsonValue {\n const [currentView, ...remainingViews] = nestedStack\n\n if (!currentView) return value\n\n const itemSchema = getArrayItemSchema(schema)\n const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n const cellSchema = getCellSchemaForArrayColumn(\n itemSchema,\n currentView.columnId\n )\n const cellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n currentView.columnId\n )\n\n if (!remainingViews.length) return cellValue\n\n return getNestedArrayValue({\n value: cellValue,\n schema: cellSchema,\n nestedStack: remainingViews,\n })\n}\n\nfunction HumanReviewArrayValueGrid({\n activeNestedSide = null,\n activeSelectionSide = null,\n label,\n nestedStackBaseDepth = 0,\n readOnly = false,\n schema,\n selectionDepth = 0,\n sharedGridSelection,\n sharedNestedStack,\n value,\n viewSide = "expected",\n metadataPath,\n onChange,\n onGridSelectionChange,\n onLocationHover,\n onNestedStackChange,\n resolveArrayItemMetadataPath,\n resolveLocation,\n}: {\n activeNestedSide?: ArrayReviewSide | null\n activeSelectionSide?: ArrayReviewSide | null\n label: string\n nestedStackBaseDepth?: number\n readOnly?: boolean\n schema: ReviewFieldSchema\n selectionDepth?: number\n sharedGridSelection?: GridSelection\n sharedNestedStack?: ArrayNestedView[]\n value: JsonValue\n viewSide?: ArrayReviewSide\n metadataPath?: string\n onChange?: (value: JsonValue) => void\n onGridSelectionChange?: (\n selection: GridSelection,\n side: ArrayReviewSide,\n depth: number\n ) => void\n onNestedStackChange?: (\n stack: ArrayNestedView[],\n side: ArrayReviewSide\n ) => void\n onLocationHover?: (location?: ReviewLocation) => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n}) {\n const rows = getArrayValue(value)\n const itemSchema = getArrayItemSchema(schema)\n const gridTheme = useHumanReviewGridTheme()\n const isDark = useIsDarkTheme()\n const [localNestedStack, setLocalNestedStack] = React.useState<\n ArrayNestedView[]\n >([])\n const [localGridSelection, setLocalGridSelection] =\n React.useState<GridSelection>(emptyGridSelection)\n const fastTextOverlayOpenRef = React.useRef(false)\n const nestedStack = sharedNestedStack ?? localNestedStack\n const visibleNestedStack = nestedStack.slice(nestedStackBaseDepth)\n const activeNestedView = visibleNestedStack[0] ?? null\n const activeNestedValue = activeNestedView\n ? getNestedArrayValue({\n value,\n schema,\n nestedStack: [activeNestedView],\n })\n : null\n const isActiveNestedSource =\n Boolean(activeNestedView) && activeNestedSide === viewSide\n const isMirroredNestedTarget =\n Boolean(activeNestedView) &&\n activeNestedSide !== null &&\n activeNestedSide !== viewSide\n const blueCellText = isDark ? "rgb(147, 197, 253)" : "rgb(37, 99, 235)"\n const selectedCellBackground = isDark\n ? "rgba(37, 99, 235, 0.2)"\n : "rgba(219, 234, 254, 0.85)"\n const mirroredCellBackground = isDark\n ? "rgba(167, 139, 250, 0.18)"\n : "rgba(237, 233, 254, 0.9)"\n const mirroredHighlightRegions = React.useMemo<\n React.ComponentProps<typeof DataEditor>["highlightRegions"]\n >(() => {\n if (\n !activeSelectionSide ||\n activeSelectionSide === viewSide ||\n selectionDepth !== nestedStackBaseDepth\n ) {\n return undefined\n }\n\n const ranges = getGridSelectionRanges(sharedGridSelection)\n if (!ranges.length) return undefined\n\n return ranges.map((range) => ({\n color: mirroredCellBackground,\n range,\n style: "dashed" as const,\n }))\n }, [\n activeSelectionSide,\n mirroredCellBackground,\n nestedStackBaseDepth,\n selectionDepth,\n sharedGridSelection,\n viewSide,\n ])\n\n const setNestedStack = React.useCallback(\n (\n updater:\n | ArrayNestedView[]\n | ((current: ArrayNestedView[]) => ArrayNestedView[])\n ) => {\n if (onNestedStackChange) {\n const nextStack =\n typeof updater === "function" ? updater(nestedStack) : updater\n\n onNestedStackChange(nextStack, viewSide)\n return\n }\n\n setLocalNestedStack(updater)\n },\n [nestedStack, onNestedStackChange, viewSide]\n )\n\n const handleGridSelectionChange = React.useCallback(\n (selection: GridSelection) => {\n flushSync(() => {\n setLocalGridSelection((current) =>\n areGridSelectionsEqual(current, selection) ? current : selection\n )\n })\n\n if (onGridSelectionChange) {\n if (\n activeSelectionSide === viewSide &&\n sharedGridSelection &&\n areGridSelectionsEqual(sharedGridSelection, selection)\n ) {\n return\n }\n\n React.startTransition(() => {\n onGridSelectionChange(selection, viewSide, nestedStackBaseDepth)\n })\n return\n }\n },\n [\n activeSelectionSide,\n nestedStackBaseDepth,\n onGridSelectionChange,\n sharedGridSelection,\n viewSide,\n ]\n )\n\n const columns = React.useMemo<GridColumn[]>(() => {\n if (itemSchema.type === "object") {\n const propertyEntries = Object.entries(itemSchema.properties ?? {})\n\n if (propertyEntries.length) {\n return propertyEntries.map(([key, propertySchema]) => ({\n id: key,\n title: propertySchema.title ?? key,\n width: isComplexSchema(propertySchema) ? 148 : 132,\n }))\n }\n }\n\n return [\n {\n id: "value",\n title: itemSchema.title ?? "Value",\n width: isComplexSchema(itemSchema) ? 148 : 180,\n },\n ]\n }, [itemSchema])\n\n const getCellContent = React.useCallback(\n ([col, row]: Item): GridCell => {\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n const cellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n columnId\n )\n const matchedNestedCell =\n activeNestedView?.rowIndex === row &&\n activeNestedView.columnId === columnId\n const nestedCellTheme: Partial<Theme> | undefined = matchedNestedCell\n ? {\n bgCell: isMirroredNestedTarget\n ? mirroredCellBackground\n : selectedCellBackground,\n textDark: blueCellText,\n }\n : undefined\n\n if (isComplexSchema(cellSchema)) {\n return {\n kind: GridCellKind.Text,\n data: summarizeComplexValue(cellValue),\n displayData: summarizeComplexValue(cellValue),\n allowOverlay: false,\n readonly: true,\n cursor: "pointer",\n activationBehaviorOverride: "double-click",\n themeOverride: {\n textDark: blueCellText,\n ...(nestedCellTheme ?? {}),\n },\n }\n }\n\n if (cellSchema.type === "boolean") {\n return {\n kind: GridCellKind.Boolean,\n data: typeof cellValue === "boolean" ? cellValue : false,\n allowOverlay: false,\n readonly: readOnly,\n }\n }\n\n if (cellSchema.type === "number" || cellSchema.type === "integer") {\n return {\n kind: GridCellKind.Number,\n data: typeof cellValue === "number" ? cellValue : undefined,\n displayData: typeof cellValue === "number" ? String(cellValue) : "",\n allowOverlay: true,\n readonly: false,\n }\n }\n\n return {\n kind: GridCellKind.Text,\n data:\n cellValue === null ||\n isJsonObject(cellValue) ||\n isJsonArray(cellValue)\n ? ""\n : String(cellValue),\n displayData:\n cellValue === null ||\n isJsonObject(cellValue) ||\n isJsonArray(cellValue)\n ? ""\n : String(cellValue),\n allowOverlay: true,\n readonly: false,\n }\n },\n [\n activeNestedView,\n blueCellText,\n columns,\n isMirroredNestedTarget,\n itemSchema,\n mirroredCellBackground,\n readOnly,\n rows,\n selectedCellBackground,\n ]\n )\n\n const updateCellValue = React.useCallback(\n ([col, row]: Item, nextCell: EditableGridCell) => {\n if (readOnly || !onChange) return\n\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n const nextValue = applyPrimitiveEdit(cellSchema, nextCell)\n\n if (nextValue === undefined) return\n\n const nextRowValue =\n itemSchema.type === "object"\n ? setObjectValue(rowValue, columnId, nextValue)\n : nextValue\n\n onChange(setArrayItemValue(value, row, nextRowValue))\n },\n [columns, itemSchema, onChange, readOnly, rows, value]\n )\n const provideEditor = React.useCallback<\n NonNullable<React.ComponentProps<typeof DataEditor>["provideEditor"]>\n >(\n (cell) => {\n if (\n cell.kind !== GridCellKind.Text &&\n cell.kind !== GridCellKind.Number\n ) {\n return undefined\n }\n\n return {\n editor: (props) => {\n if (\n props.value.kind !== GridCellKind.Text &&\n props.value.kind !== GridCellKind.Number\n ) {\n return null\n }\n\n return (\n <HumanReviewTextOverlayEditor\n {...(props as React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n >)}\n overlayOpenRef={fastTextOverlayOpenRef}\n readOnly={readOnly}\n />\n )\n },\n }\n },\n [readOnly]\n )\n const handleOutsideClick = React.useCallback(\n () => !fastTextOverlayOpenRef.current,\n []\n )\n const handleItemHovered = React.useCallback(\n (args: GridMouseEventArgs) => {\n if (!onLocationHover || !resolveLocation || !metadataPath) return\n\n if (args.kind !== "cell") {\n onLocationHover(undefined)\n return\n }\n\n const [col, row] = args.location\n const column = columns[col]\n const rowValue = rows[row]\n if (!column || rowValue === undefined) {\n onLocationHover(undefined)\n return\n }\n\n const columnId = String(column.id ?? "value")\n const rowMetadataPath = resolveArrayItemMetadataPath\n ? resolveArrayItemMetadataPath(metadataPath, row, rowValue)\n : `${metadataPath}[${row}]`\n if (!rowMetadataPath) {\n onLocationHover(undefined)\n return\n }\n\n const propertyMetadataPath =\n itemSchema.type === "object"\n ? `${rowMetadataPath}.${columnId}`\n : rowMetadataPath\n\n onLocationHover(\n resolveLocation(propertyMetadataPath) ??\n resolveLocation(rowMetadataPath)\n )\n },\n [\n columns,\n itemSchema.type,\n metadataPath,\n onLocationHover,\n resolveArrayItemMetadataPath,\n resolveLocation,\n rows,\n ]\n )\n\n const openNestedCell = React.useCallback(\n ([col, row]: Item) => {\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n\n if (!isComplexSchema(cellSchema)) return\n\n setNestedStack((current) => {\n const nextView = {\n rowIndex: row,\n columnId,\n title: `${column?.title ?? columnId} / row ${row + 1}`,\n schema: cellSchema,\n value: getCellValueForArrayColumn(rowValue, itemSchema, columnId),\n }\n const currentView = current[nestedStackBaseDepth]\n\n if (\n currentView?.rowIndex === nextView.rowIndex &&\n currentView.columnId === nextView.columnId\n ) {\n return current\n }\n\n return [...current.slice(0, nestedStackBaseDepth), nextView]\n })\n },\n [columns, itemSchema, nestedStackBaseDepth, rows, setNestedStack]\n )\n\n const updateNestedValue = React.useCallback(\n (nextNestedValue: JsonValue) => {\n if (!activeNestedView || readOnly || !onChange) return\n\n onChange(\n setNestedArrayValue({\n value,\n schema,\n nestedStack: visibleNestedStack.slice(0, 1),\n nextNestedValue,\n })\n )\n setNestedStack((current) =>\n current.map((view, index) =>\n index === nestedStackBaseDepth\n ? { ...view, value: nextNestedValue }\n : view\n )\n )\n },\n [\n activeNestedView,\n nestedStackBaseDepth,\n onChange,\n readOnly,\n schema,\n setNestedStack,\n value,\n visibleNestedStack,\n ]\n )\n\n return (\n <div\n onMouseLeave={() => onLocationHover?.(undefined)}\n className={cn(\n "relative overflow-hidden rounded-md border bg-background transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:shadow-[0_0_0_1px_rgb(59_130_246_/_8%)] hover:border-blue-500/50",\n isActiveNestedSource &&\n "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_10%)]"\n )}\n >\n <div>\n <div className="flex h-8 items-center justify-between gap-2 border-b px-2 text-[11px] font-medium text-muted-foreground">\n <span>{label}</span>\n <span>{rows.length} rows</span>\n </div>\n <div className="h-[220px]">\n <DataEditor\n columns={columns}\n rows={rows.length}\n getCellContent={getCellContent}\n cellActivationBehavior="double-click"\n gridSelection={localGridSelection}\n highlightRegions={mirroredHighlightRegions}\n onCellEdited={updateCellValue}\n onCellActivated={openNestedCell}\n onGridSelectionChange={handleGridSelectionChange}\n onItemHovered={handleItemHovered}\n provideEditor={provideEditor}\n isOutsideClick={handleOutsideClick}\n rowMarkers="number"\n smoothScrollX\n smoothScrollY\n theme={gridTheme}\n width="100%"\n height="100%"\n rowHeight={32}\n headerHeight={34}\n />\n </div>\n </div>\n {activeNestedView ? (\n <div className="absolute inset-0 z-10 flex flex-col bg-background">\n <div className="flex h-8 items-center gap-2 border-b px-2">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="size-6 text-muted-foreground"\n onClick={() =>\n setNestedStack((current) =>\n current.slice(\n 0,\n Math.max(nestedStackBaseDepth, current.length - 1)\n )\n )\n }\n aria-label="Back to parent array"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />\n </Button>\n <div className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">\n {activeNestedView.title}\n </div>\n </div>\n <div className="min-h-0 flex-1 overflow-auto p-2">\n {activeNestedView.schema.type === "array" ? (\n <HumanReviewArrayValueGrid\n label={\n activeNestedView.schema.title ?? activeNestedView.columnId\n }\n nestedStackBaseDepth={nestedStackBaseDepth + 1}\n readOnly={readOnly}\n schema={activeNestedView.schema}\n sharedGridSelection={sharedGridSelection}\n sharedNestedStack={sharedNestedStack}\n value={activeNestedValue}\n viewSide={viewSide}\n activeNestedSide={activeNestedSide}\n activeSelectionSide={activeSelectionSide}\n selectionDepth={selectionDepth}\n onChange={updateNestedValue}\n onGridSelectionChange={onGridSelectionChange}\n onNestedStackChange={onNestedStackChange}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n ) : (\n <HumanReviewObjectValueEditor\n schema={activeNestedView.schema}\n value={activeNestedValue}\n originalValue={activeNestedValue}\n readOnly={readOnly}\n onChange={updateNestedValue}\n />\n )}\n </div>\n </div>\n ) : null}\n </div>\n )\n}\n\nfunction HumanReviewObjectValueEditor({\n schema,\n value,\n originalValue,\n readOnly = false,\n onChange,\n}: {\n schema: ReviewFieldSchema\n value: JsonValue\n originalValue: JsonValue\n readOnly?: boolean\n onChange: (value: JsonValue) => void\n}) {\n const propertyEntries = Object.entries(schema.properties ?? {})\n\n if (!propertyEntries.length) {\n return (\n <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n No properties\n </div>\n )\n }\n\n return (\n <div className="space-y-2">\n {propertyEntries.map(([propertyKey, propertySchema]) => (\n <HumanReviewFieldCard\n key={propertyKey}\n field={{\n key: propertyKey,\n schema: propertySchema,\n actual: getObjectValue(originalValue, propertyKey),\n expected: getObjectValue(originalValue, propertyKey),\n }}\n value={getObjectValue(value, propertyKey)}\n originalValue={getObjectValue(originalValue, propertyKey)}\n readOnly={readOnly}\n onChange={(childValue) =>\n !readOnly &&\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onUndo={() =>\n !readOnly &&\n onChange(\n setObjectValue(\n value,\n propertyKey,\n getObjectValue(originalValue, propertyKey)\n )\n )\n }\n onSetNull={() =>\n !readOnly && onChange(setObjectValue(value, propertyKey, null))\n }\n />\n ))}\n </div>\n )\n}\n\ntype HumanReviewFieldCardProps = {\n field: ReviewField\n value: JsonValue\n originalValue: JsonValue\n active?: boolean\n activeFieldKey?: string\n readOnly?: boolean\n onChange: (value: JsonValue) => void\n onFieldFocus?: (field: ReviewField) => void\n onLocationHover?: (location?: ReviewLocation) => void\n onUndo: () => void\n onSetNull: () => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n}\n\nfunction areHumanReviewFieldCardPropsEqual(\n previous: HumanReviewFieldCardProps,\n next: HumanReviewFieldCardProps\n) {\n return (\n previous.field === next.field &&\n Object.is(previous.value, next.value) &&\n Object.is(previous.originalValue, next.originalValue) &&\n previous.active === next.active &&\n previous.activeFieldKey === next.activeFieldKey &&\n previous.readOnly === next.readOnly &&\n previous.onFieldFocus === next.onFieldFocus &&\n previous.onLocationHover === next.onLocationHover &&\n previous.resolveArrayItemMetadataPath ===\n next.resolveArrayItemMetadataPath &&\n previous.resolveLocation === next.resolveLocation\n )\n}\n\nconst HumanReviewFieldCard = React.memo(\n HumanReviewFieldCardBase,\n areHumanReviewFieldCardPropsEqual\n)\n\nfunction HumanReviewFieldCardBase({\n field,\n value,\n originalValue,\n active,\n activeFieldKey,\n readOnly = false,\n onChange,\n onFieldFocus,\n onLocationHover,\n onUndo,\n onSetNull,\n resolveArrayItemMetadataPath,\n resolveLocation,\n}: HumanReviewFieldCardProps) {\n const modified = !jsonValuesEqual(value, originalValue)\n const Icon = getFieldIcon(field.schema.type)\n const propertyEntries = Object.entries(field.schema.properties ?? {})\n const [syncedArrayNestedView, setSyncedArrayNestedView] =\n React.useState<SyncedArrayNestedView>(EMPTY_SYNCED_ARRAY_NESTED_VIEW)\n const [syncedArraySelection, setSyncedArraySelection] =\n React.useState<SyncedArraySelection>(EMPTY_SYNCED_ARRAY_SELECTION)\n const updateSyncedArrayNestedView = React.useCallback(\n (stack: ArrayNestedView[], side: ArrayReviewSide) => {\n const activeSide = stack.length ? side : null\n\n setSyncedArrayNestedView((current) =>\n current.activeSide === activeSide &&\n areArrayNestedViewsEqual(current.stack, stack)\n ? current\n : {\n activeSide,\n stack,\n }\n )\n },\n []\n )\n const updateSyncedArraySelection = React.useCallback(\n (gridSelection: GridSelection, side: ArrayReviewSide, depth: number) => {\n const activeSide = gridSelection.current ? side : null\n\n setSyncedArraySelection((current) =>\n current.activeSide === activeSide &&\n current.depth === depth &&\n areGridSelectionsEqual(current.gridSelection, gridSelection)\n ? current\n : {\n activeSide,\n depth,\n gridSelection,\n }\n )\n },\n []\n )\n const focusAndHoverField = React.useCallback(() => {\n onFieldFocus?.(field)\n onLocationHover?.(getReviewFieldLocation(field, resolveLocation))\n }, [field, onFieldFocus, onLocationHover, resolveLocation])\n\n return (\n <div\n tabIndex={0}\n onFocusCapture={focusAndHoverField}\n onMouseEnter={focusAndHoverField}\n onMouseLeave={() => onLocationHover?.(undefined)}\n className={cn(\n "rounded-lg border bg-background p-3 transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:bg-blue-500/5 hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",\n active &&\n "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_8%)]"\n )}\n >\n <div className="mb-3 flex min-h-8 items-start justify-between gap-3">\n <div className="min-w-0">\n <div className="flex min-w-0 items-center gap-2">\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">\n {field.schema.title ?? field.key}\n </div>\n </div>\n <span\n className={cn(\n "size-2 shrink-0 rounded-full bg-amber-400 transition-opacity",\n !modified && "opacity-0"\n )}\n />\n </div>\n <div className="truncate text-xs text-muted-foreground">\n {field.key}\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-1">\n {!readOnly && modified ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="text-muted-foreground"\n onClick={onUndo}\n aria-label={`Undo ${field.key}`}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Revert changes</TooltipContent>\n </Tooltip>\n ) : null}\n {!readOnly ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="text-muted-foreground"\n onClick={onSetNull}\n aria-label={`Set ${field.key} to null`}\n >\n <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Set to NULL</TooltipContent>\n </Tooltip>\n ) : null}\n <div className="flex h-6 items-center gap-1 rounded-md border bg-muted/50 px-1.5 text-xs text-muted-foreground">\n <HugeiconsIcon icon={Icon} className="size-3.5" />\n {field.schema.type}\n </div>\n </div>\n </div>\n {field.schema.type === "object" ? (\n <div className="rounded-md border bg-muted/25 p-2">\n <div className="mb-2 flex items-center justify-between gap-3 text-[11px] font-medium text-muted-foreground">\n <span>Properties</span>\n <span>{propertyEntries.length} fields</span>\n </div>\n <div className="space-y-2">\n {propertyEntries.length ? (\n propertyEntries.map(([propertyKey, schema]) => {\n const childField: ReviewField = {\n key: `${field.key}.${propertyKey}`,\n schema,\n actual: getObjectValue(field.actual, propertyKey),\n expected: getObjectValue(originalValue, propertyKey),\n metadataPath: `${field.metadataPath ?? field.key}.${propertyKey}`,\n }\n\n return (\n <HumanReviewFieldCard\n key={childField.key}\n field={childField}\n value={getObjectValue(value, propertyKey)}\n originalValue={childField.expected}\n active={childField.key === activeFieldKey}\n activeFieldKey={activeFieldKey}\n readOnly={readOnly}\n onChange={(childValue) =>\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onFieldFocus={onFieldFocus}\n onLocationHover={onLocationHover}\n onUndo={() =>\n onChange(\n setObjectValue(value, propertyKey, childField.expected)\n )\n }\n onSetNull={() =>\n onChange(setObjectValue(value, propertyKey, null))\n }\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n )\n })\n ) : (\n <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n No properties\n </div>\n )}\n </div>\n </div>\n ) : field.schema.type === "array" ? (\n <div className="grid gap-2">\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Actual"\n metadataPath={field.metadataPath ?? field.key}\n readOnly\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n schema={field.schema}\n selectionDepth={syncedArraySelection.depth}\n sharedGridSelection={syncedArraySelection.gridSelection}\n sharedNestedStack={syncedArrayNestedView.stack}\n value={field.actual}\n viewSide="actual"\n onGridSelectionChange={updateSyncedArraySelection}\n onLocationHover={onLocationHover}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Expected"\n metadataPath={field.metadataPath ?? field.key}\n readOnly={readOnly}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n schema={field.schema}\n selectionDepth={syncedArraySelection.depth}\n sharedGridSelection={syncedArraySelection.gridSelection}\n sharedNestedStack={syncedArrayNestedView.stack}\n value={value}\n viewSide="expected"\n onChange={onChange}\n onGridSelectionChange={updateSyncedArraySelection}\n onLocationHover={onLocationHover}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n </div>\n ) : (\n <div className="grid gap-2 sm:grid-cols-2">\n <div className="rounded-md border bg-muted/30 p-2">\n {field.schema.description ? (\n <p className="mb-2 text-xs text-muted-foreground">\n {field.schema.description}\n </p>\n ) : null}\n <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n Actual\n </div>\n <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">\n {formatValue(field.actual)}\n </div>\n </div>\n <div className="rounded-md border bg-muted/30 p-2">\n <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n Expected\n </div>\n <HumanReviewValueInput\n readOnly={readOnly}\n schema={field.schema}\n value={getPrimitiveValue(value)}\n onChange={onChange}\n />\n </div>\n </div>\n )}\n </div>\n )\n}\n\nexport function HumanReviewHighlight({\n location,\n}: {\n location: ReviewLocation\n}) {\n const area = location.area\n\n return (\n <div\n className={cn(\n "pointer-events-none absolute z-10 border",\n REVIEW_HIGHLIGHT_STYLE\n )}\n style={{\n left: `${area.left}%`,\n top: `${area.top}%`,\n width: `${area.width}%`,\n height: `${area.height}%`,\n }}\n />\n )\n}\n\nexport function JsonDiffView({\n actual,\n expected,\n theme = "light",\n}: {\n actual: JsonObject\n expected: JsonObject\n theme?: HumanReviewTheme\n}) {\n const oldFile = React.useMemo(\n () => ({\n name: "actual.json",\n contents: formatJson(actual),\n lang: "json",\n }),\n [actual]\n )\n const newFile = React.useMemo(\n () => ({\n name: "expected.json",\n contents: formatJson(expected),\n lang: "json",\n }),\n [expected]\n )\n\n return (\n <Virtualizer\n className="h-full overflow-auto bg-surface/60"\n contentClassName="min-w-full"\n >\n <div className="human-review-diff h-full text-xs">\n <MultiFileDiff\n className="block min-w-full"\n oldFile={oldFile}\n newFile={newFile}\n options={{\n diffStyle: "split",\n disableFileHeader: true,\n diffIndicators: "bars",\n hunkSeparators: "line-info-basic",\n overflow: "wrap",\n themeType: theme,\n theme: {\n light: "pierre-light-soft",\n dark: "pierre-dark-soft",\n },\n }}\n />\n </div>\n </Virtualizer>\n )\n}\n\nexport function HumanReviewPanel({\n fields = REVIEW_FIELDS,\n activeFieldKey,\n className,\n onFieldFocus,\n onLocationHover,\n resolveArrayItemMetadataPath,\n resolveLocation,\n theme = "light",\n}: {\n fields?: ReviewField[]\n activeFieldKey?: string\n className?: string\n onFieldFocus?: (field: ReviewField) => void\n onLocationHover?: (location?: ReviewLocation) => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n theme?: HumanReviewTheme\n} = {}) {\n const [activeTab, setActiveTab] = React.useState("form")\n const actualValues = React.useMemo(\n () => valuesFromFields(fields, "actual"),\n [fields]\n )\n const initialExpectedValues = React.useMemo(\n () => valuesFromFields(fields, "expected"),\n [fields]\n )\n const [expected, setExpected] = React.useState<JsonObject>(\n initialExpectedValues\n )\n\n React.useEffect(() => {\n setExpected(initialExpectedValues)\n }, [initialExpectedValues])\n\n const updateValue = React.useCallback((key: string, value: JsonValue) => {\n setExpected((current) =>\n Object.is(current[key], value) ? current : { ...current, [key]: value }\n )\n }, [])\n\n return (\n <TooltipProvider delay={200}>\n <Tabs\n value={activeTab}\n onValueChange={setActiveTab}\n className={cn("flex h-[560px] flex-col gap-0 bg-background", className)}\n >\n <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">\n <TabsList className="h-8 sm:h-7">\n <TabsTrigger value="form" className="h-7 sm:h-6">\n <HugeiconsIcon icon={TextCheckIcon} className="size-4" />\n Form\n </TabsTrigger>\n <TabsTrigger value="json" className="h-7 sm:h-6">\n <HugeiconsIcon icon={SourceCodeSquareIcon} className="size-4" />\n JSON\n </TabsTrigger>\n </TabsList>\n </div>\n <TabsContent value="form" keepMounted className="min-h-0 flex-1">\n <ScrollArea className="h-full" scrollFade>\n <div className="space-y-3 p-3">\n {fields.map((field) => (\n <HumanReviewFieldCard\n key={field.key}\n field={field}\n value={expected[field.key] ?? null}\n originalValue={field.expected}\n active={\n field.key === activeFieldKey ||\n activeFieldKey?.startsWith(`${field.key}.`)\n }\n activeFieldKey={activeFieldKey}\n onChange={(value) => updateValue(field.key, value)}\n onFieldFocus={onFieldFocus}\n onLocationHover={onLocationHover}\n onUndo={() => updateValue(field.key, field.expected)}\n onSetNull={() => updateValue(field.key, null)}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n ))}\n </div>\n </ScrollArea>\n </TabsContent>\n <TabsContent value="json" keepMounted className="min-h-0 flex-1">\n <JsonDiffView\n actual={actualValues}\n expected={expected}\n theme={theme}\n />\n </TabsContent>\n </Tabs>\n </TooltipProvider>\n )\n}\n'
export function HumanReviewSource() {
return (
diff --git a/apps/v4/components/pdf-block-resizable-shell.tsx b/apps/v4/components/pdf-block-resizable-shell.tsx
index 2a392c6..5b87be8 100644
--- a/apps/v4/components/pdf-block-resizable-shell.tsx
+++ b/apps/v4/components/pdf-block-resizable-shell.tsx
@@ -110,34 +110,6 @@ export function PdfBlockResizableShell({
rightMaxSize = 52,
rightMinSize = 24,
}: PdfBlockResizableShellProps) {
- const [isMounted, setIsMounted] = React.useState(false)
-
- React.useEffect(() => {
- setIsMounted(true)
- }, [])
-
- if (!isMounted) {
- return (
- <PdfBlockResizableShellLayout
- className={className}
- heightClassName={heightClassName}
- left={left}
- leftDefaultSize={
- leftDefaultSize ??
- (initialOrientation === "horizontal" ? 100 - rightDefaultSize : 62)
- }
- leftMinSize={leftMinSize}
- orientation={initialOrientation}
- right={right}
- rightDefaultSize={
- initialOrientation === "horizontal" ? rightDefaultSize : 38
- }
- rightMaxSize={initialOrientation === "horizontal" ? rightMaxSize : 66}
- rightMinSize={initialOrientation === "horizontal" ? rightMinSize : 24}
- />
- )
- }
-
return (
<PdfBlockResizableShellWithSavedLayout
autoSaveId={autoSaveId}
diff --git a/apps/v4/components/pdf-viewer-blocks.tsx b/apps/v4/components/pdf-viewer-blocks.tsx
index a0ee3ac..5b29153 100644
--- a/apps/v4/components/pdf-viewer-blocks.tsx
+++ b/apps/v4/components/pdf-viewer-blocks.tsx
@@ -73,6 +73,7 @@ const blockViewportSizes: Array<{
]
const BLOCK_VIEWPORT_HEIGHT_CLASS = "h-[680px]"
+const BLOCK_PREVIEW_LAZY_ROOT_MARGIN = "900px 0px"
const OcrBlocksBlock = dynamic(
() =>
@@ -125,36 +126,25 @@ function PdfViewerBlockPreview({
const [previewKey, setPreviewKey] = React.useState(0)
const [view, setView] = React.useState<BlockView>("preview")
const [hasOpenedCode, setHasOpenedCode] = React.useState(false)
+ const [codeScrollResetKey, setCodeScrollResetKey] = React.useState(0)
const [activeViewport, setActiveViewport] =
React.useState<BlockViewportSize>("desktop")
const [isCommandCopied, setIsCommandCopied] = React.useState(false)
const [activeFile, setActiveFile] = React.useState<string | null>(
codeSamples[0]?.targetPath ?? null
)
+ const [articleRef, shouldMountPreview] = useLazyBlockPreview()
const isMounted = useMounted()
const previewPanelRef = React.useRef<PanelImperativeHandle>(null)
- const codePanelMountFrameRef = React.useRef<number | null>(null)
const Preview = block.component
const isDesktopViewport = useMediaQuery("(min-width: 768px)")
const previewHeightClassName =
block.previewHeightClassName ?? BLOCK_VIEWPORT_HEIGHT_CLASS
- const scheduleCodePanelMount = React.useCallback(() => {
- if (hasOpenedCode || codePanelMountFrameRef.current !== null) return
-
- codePanelMountFrameRef.current = window.requestAnimationFrame(() => {
- codePanelMountFrameRef.current = window.requestAnimationFrame(() => {
- codePanelMountFrameRef.current = null
- setHasOpenedCode(true)
- })
- })
- }, [hasOpenedCode])
-
function setBlockView(nextView: BlockView) {
- if (nextView === "code" && !hasOpenedCode) {
- setView(nextView)
- scheduleCodePanelMount()
- return
+ if (nextView === "code") {
+ setHasOpenedCode(true)
+ setCodeScrollResetKey((key) => key + 1)
}
setView(nextView)
@@ -166,14 +156,6 @@ function PdfViewerBlockPreview({
previewPanelRef.current?.resize(`${viewport.panelSize}%`)
}
- React.useEffect(() => {
- return () => {
- if (codePanelMountFrameRef.current !== null) {
- window.cancelAnimationFrame(codePanelMountFrameRef.current)
- }
- }
- }, [])
-
React.useEffect(() => {
if (!isCommandCopied) return
@@ -210,7 +192,7 @@ function PdfViewerBlockPreview({
}
return (
- <article id={block.id} className="scroll-mt-24 space-y-2">
+ <article ref={articleRef} id={block.id} className="scroll-mt-24 space-y-2">
<div
data-view={view}
className="group/block-preview overflow-hidden rounded-xl"
@@ -313,7 +295,7 @@ function PdfViewerBlockPreview({
Preview={Preview}
isMounted={isMounted}
previewKey={previewKey}
- shouldRenderPreview={isDesktopViewport}
+ shouldRenderPreview={isDesktopViewport && shouldMountPreview}
/>
</ResizablePanel>
<ResizableHandle className="relative w-3 bg-transparent p-0 after:absolute after:top-1/2 after:right-0 after:h-8 after:w-1.5 after:-translate-y-1/2 after:rounded-full after:bg-background after:shadow-sm after:ring-1 after:ring-border after:transition-all after:hover:h-10" />
@@ -325,17 +307,17 @@ function PdfViewerBlockPreview({
Preview={Preview}
isMounted={isMounted}
previewKey={previewKey}
- shouldRenderPreview={!isDesktopViewport}
+ shouldRenderPreview={!isDesktopViewport && shouldMountPreview}
/>
</div>
</div>
- {view === "code" && !hasOpenedCode ? <BlockCodePanelShell /> : null}
{hasOpenedCode ? (
<div className={view === "code" ? "block" : "hidden"}>
<BlockCodePanel
codeSamples={codeSamples}
activeFile={activeFile}
onActiveFileChange={setActiveFile}
+ scrollResetKey={codeScrollResetKey}
/>
</div>
) : null}
@@ -344,6 +326,37 @@ function PdfViewerBlockPreview({
)
}
+function useLazyBlockPreview() {
+ const [node, setNode] = React.useState<HTMLElement | null>(null)
+ const [shouldMountPreview, setShouldMountPreview] = React.useState(false)
+
+ React.useEffect(() => {
+ if (shouldMountPreview) return
+ if (!node) return
+
+ if (!("IntersectionObserver" in window)) {
+ setShouldMountPreview(true)
+ return
+ }
+
+ const observer = new IntersectionObserver(
+ ([entry]) => {
+ if (!entry?.isIntersecting) return
+
+ setShouldMountPreview(true)
+ observer.disconnect()
+ },
+ { rootMargin: BLOCK_PREVIEW_LAZY_ROOT_MARGIN }
+ )
+
+ observer.observe(node)
+
+ return () => observer.disconnect()
+ }, [node, shouldMountPreview])
+
+ return [setNode, shouldMountPreview] as const
+}
+
function BlockPreviewPlaceholder() {
return <div className="h-full min-h-[560px] bg-muted/20" />
}
@@ -403,31 +416,16 @@ const BlockPreviewSurface = React.memo(function BlockPreviewSurface({
return <Preview key={previewKey} />
})
-function BlockCodePanelShell() {
- return (
- <div
- className={`flex ${BLOCK_VIEWPORT_HEIGHT_CLASS} overflow-hidden rounded-xl border bg-code text-code-foreground`}
- >
- <div className="hidden w-72 shrink-0 border-r bg-code md:block">
- <div className="flex h-12 items-center border-b px-4 text-sm font-medium">
- Files
- </div>
- </div>
- <div className="flex min-w-0 flex-1 flex-col">
- <div className="h-12 border-b" />
- </div>
- </div>
- )
-}
-
function BlockCodePanel({
codeSamples,
activeFile,
onActiveFileChange,
+ scrollResetKey,
}: {
codeSamples: BlockCodeSample[]
activeFile: string | null
onActiveFileChange: (file: string) => void
+ scrollResetKey: React.Key
}) {
const activeCodeSample =
codeSamples.find((sample) => sample.targetPath === activeFile) ??
@@ -467,19 +465,30 @@ function BlockCodePanel({
event="copy_block_code"
/>
</div>
- <BlockCodeContent code={activeCodeSample} />
+ <BlockCodeContent
+ code={activeCodeSample}
+ scrollResetKey={scrollResetKey}
+ />
</div>
</div>
)
}
-function BlockCodeContent({ code }: { code: BlockCodeSample }) {
+function BlockCodeContent({
+ code,
+ scrollResetKey,
+}: {
+ code: BlockCodeSample
+ scrollResetKey: React.Key
+}) {
return (
<HighlightedCodeBlock
- key={code.targetPath}
code={code.content}
fileName={code.targetPath}
language={code.language}
+ lazy={false}
+ renderFallbackCode
+ scrollResetKey={scrollResetKey}
showCopy={false}
className="min-h-0 flex-1 rounded-none border-0"
maxHeightClassName="h-full max-h-none"
diff --git a/apps/v4/components/schema-builder-demo.tsx b/apps/v4/components/schema-builder-demo.tsx
new file mode 100644
index 0000000..8098bc6
--- /dev/null
+++ b/apps/v4/components/schema-builder-demo.tsx
@@ -0,0 +1,22 @@
+"use client"
+
+import { SchemaBuilderPanel } from "@/components/ui/schema-builder"
+import { DocsViewCodeBlock } from "@/components/docs-code-block"
+
+export function SchemaBuilderDemo() {
+ return (
+ <div
+ data-slot="component-preview"
+ className="group relative mt-4 mb-12 flex flex-col overflow-hidden rounded-xl border"
+ >
+ <SchemaBuilderPanel className="h-[620px]" />
+ <DocsViewCodeBlock code={schemaBuilderDemoCode} />
+ </div>
+ )
+}
+
+const schemaBuilderDemoCode = `import { SchemaBuilderPanel } from "@/components/ui/schema-builder";
+
+export function SchemaBuilderExample() {
+ return <SchemaBuilderPanel className="h-[620px]" />;
+}`
diff --git a/apps/v4/components/schema-builder-docs.tsx b/apps/v4/components/schema-builder-docs.tsx
new file mode 100644
index 0000000..a6844c2
--- /dev/null
+++ b/apps/v4/components/schema-builder-docs.tsx
@@ -0,0 +1,20 @@
+import { readFileSync } from "node:fs"
+import { join } from "node:path"
+
+import { DocsSourceCodeBlock } from "@/components/docs-code-block"
+
+export { SchemaBuilderDemo } from "@/components/schema-builder-demo"
+
+export function SchemaBuilderSource() {
+ const code = readFileSync(
+ join(process.cwd(), "registry/new-york-v4/ui/schema-builder.tsx"),
+ "utf8"
+ )
+
+ return (
+ <DocsSourceCodeBlock
+ code={code}
+ fileName="components/ui/schema-builder.tsx"
+ />
+ )
+}
diff --git a/apps/v4/components/ui/schema-builder.tsx b/apps/v4/components/ui/schema-builder.tsx
new file mode 100644
index 0000000..d1ed6bb
--- /dev/null
+++ b/apps/v4/components/ui/schema-builder.tsx
@@ -0,0 +1,18 @@
+"use client"
+
+export {
+ SAMPLE_SCHEMA,
+ SchemaBuilderPanel,
+ SchemaJsonView,
+ serializeSchema,
+ type SchemaBuilderArrayItemType,
+ type SchemaBuilderArrayScalarType,
+ type SchemaBuilderEnumValue,
+ type SchemaBuilderFieldType,
+ type SchemaBuilderProperty,
+ type SchemaBuilderScalarType,
+ type SchemaBuilderSchema,
+ type SchemaBuilderTheme,
+ type SerializedSchema,
+ type SerializedSchemaProperty,
+} from "@/registry/new-york-v4/ui/schema-builder"
diff --git a/apps/v4/content/docs/components/meta.json b/apps/v4/content/docs/components/meta.json
index 4292545..cf71842 100644
--- a/apps/v4/content/docs/components/meta.json
+++ b/apps/v4/content/docs/components/meta.json
@@ -10,6 +10,7 @@
"[CSV Viewer](/docs/components/csv-tsv-viewer)",
"file-upload",
"human-review",
+ "schema-builder",
"file-thumbnail",
"ocr-blocks",
"e-signature",
diff --git a/apps/v4/content/docs/components/schema-builder.mdx b/apps/v4/content/docs/components/schema-builder.mdx
new file mode 100644
index 0000000..f389d38
--- /dev/null
+++ b/apps/v4/content/docs/components/schema-builder.mdx
@@ -0,0 +1,85 @@
+---
+title: Schema Builder
+description: Build extraction schemas with a table editor and synchronized JSON view.
+component: true
+---
+
+Schema Builder provides a field table for defining extraction schema keys, JSON
+types, descriptions, enums, nested objects, and arrays.
+
+<SchemaBuilderDemo />
+
+## Installation
+
+<CodeTabs>
+
+<TabsList>
+ <TabsTrigger value="cli">Command</TabsTrigger>
+ <TabsTrigger value="manual">Manual</TabsTrigger>
+</TabsList>
+<TabsContent value="cli">
+
+```bash
+npx shadcn@latest add https://ui.extend.ai/r/schema-builder.json
+```
+
+</TabsContent>
+
+<TabsContent value="manual">
+
+<Steps className="mb-0 pt-2">
+
+<Step>Install the following dependencies:</Step>
+
+```bash
+npm install @dnd-kit/core@^6.3.1 @dnd-kit/sortable@^10.0.0 @dnd-kit/utilities@^3.2.2 @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6 @pierre/diffs@^1.2.7 [email protected]
+```
+
+<Step>Copy and paste the following code into your project.</Step>
+
+<SchemaBuilderSource />
+
+<Step>Update the import paths to match your project setup.</Step>
+
+</Steps>
+
+</TabsContent>
+
+</CodeTabs>
+
+## Useful behaviors
+
+- Form and JSON tabs share the same schema state.
+- Type selector includes scalar JSON types, enum, object, and array options.
+- Property keys can be reordered or dragged into and out of object and array object schemas.
+- Enum values can be reordered.
+- Enum rows support editable values and descriptions.
+- Object rows render a nested schema table below the parent row.
+- Array rows support object, enum, or scalar item types; object arrays render a nested item schema table and enum arrays render an enum table.
+- JSON view matches the app code block surface and follows the current light or dark theme.
+
+## API Reference
+
+### SchemaBuilderPanel
+
+The SchemaBuilderPanel component renders the editable schema table and a JSON view for the serialized schema.
+
+| Prop | Type | Default | Required |
+| ---------------- | --------------------------------------- | ------------- | -------- |
+| `className` | `string` | `-` | No |
+| `defaultSchema` | `SchemaBuilderSchema` | sample schema | No |
+| `schema` | `SchemaBuilderSchema` | `-` | No |
+| `onSchemaChange` | `(schema: SchemaBuilderSchema) => void` | `-` | No |
+| `theme` | `"light" \| "dark"` | app theme | No |
+
+### SchemaBuilderProperty
+
+| Prop | Type | Default | Required |
+| ------------- | ------------------------------------ | ------- | -------- |
+| `id` | `string` | `-` | Yes |
+| `key` | `string` | `-` | Yes |
+| `type` | `SchemaBuilderFieldType` | `-` | Yes |
+| `description` | `string` | `-` | Yes |
+| `enumValues` | `SchemaBuilderEnumValue[]` | `-` | No |
+| `properties` | `SchemaBuilderProperty[]` | `-` | No |
+| `items` | `{ type; properties?; enumValues? }` | `-` | No |
diff --git a/apps/v4/mdx-components.tsx b/apps/v4/mdx-components.tsx
index 9f8e5be..013b493 100644
--- a/apps/v4/mdx-components.tsx
+++ b/apps/v4/mdx-components.tsx
@@ -11,8 +11,8 @@ import { CodeCollapsibleWrapper } from "@/components/code-collapsible-wrapper"
import { CodeTabs } from "@/components/code-tabs"
import { ComponentsList } from "@/components/components-list"
import { CopyButton } from "@/components/copy-button"
-import { DocsMdxCodeBlock } from "@/components/docs-code-block"
import { CsvViewerDemo, CsvViewerSource } from "@/components/csv-viewer-docs"
+import { DocsMdxCodeBlock } from "@/components/docs-code-block"
import {
DocumentSplitsDemo,
DocumentSplitsSource,
@@ -36,6 +36,10 @@ import {
import { getIconForLanguageExtension } from "@/components/icons"
import { OcrBlocksDemo, OcrBlocksSource } from "@/components/ocr-blocks-docs"
import { PdfViewerDemo, PdfViewerSource } from "@/components/pdf-viewer-docs"
+import {
+ SchemaBuilderDemo,
+ SchemaBuilderSource,
+} from "@/components/schema-builder-docs"
import { XlsxEditorDemo, XlsxEditorSource } from "@/components/xlsx-editor-docs"
import { XlsxViewerDemo, XlsxViewerSource } from "@/components/xlsx-viewer-docs"
import {
@@ -396,6 +400,8 @@ export const mdxComponents = {
FileUploadSource,
HumanReviewDemo,
HumanReviewSource,
+ SchemaBuilderDemo,
+ SchemaBuilderSource,
OcrBlocksDemo,
OcrBlocksSource,
PdfViewerDemo,
diff --git a/apps/v4/registry.json b/apps/v4/registry.json
index c2e4af8..d476a92 100644
--- a/apps/v4/registry.json
+++ b/apps/v4/registry.json
@@ -854,6 +854,37 @@
}
]
},
+ {
+ "name": "schema-builder",
+ "type": "registry:ui",
+ "title": "Schema Builder",
+ "description": "A JSON schema builder with form and JSON views for extraction schemas.",
+ "dependencies": [
+ "@dnd-kit/core@^6.3.1",
+ "@dnd-kit/sortable@^10.0.0",
+ "@dnd-kit/utilities@^3.2.2",
+ "@hugeicons/core-free-icons@^4.2.0",
+ "@hugeicons/react@^1.1.6",
+ "@pierre/diffs@^1.2.7",
+ ],
+ "registryDependencies": [
+ "button",
+ "collapsible",
+ "dropdown-menu",
+ "scroll-area",
+ "tabs",
+ "utils"
+ ],
+ "categories": ["documents"],
+ "files": [
+ {
+ "path": "registry/new-york-v4/ui/schema-builder.tsx",
+ "type": "registry:ui",
+ "target": "@ui/schema-builder.tsx"
+ }
+ ]
+ },
{
"name": "human-review-block",
"type": "registry:block",
diff --git a/apps/v4/registry/new-york-v4/ui/human-review.tsx b/apps/v4/registry/new-york-v4/ui/human-review.tsx
index 8d410e9..a6d1702 100644
--- a/apps/v4/registry/new-york-v4/ui/human-review.tsx
+++ b/apps/v4/registry/new-york-v4/ui/human-review.tsx
@@ -107,36 +107,6 @@ export type ReviewMetadataEntry = {
const DEFAULT_ZOOM = 0.75
const REVIEW_HIGHLIGHT_STYLE =
"border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"
-const DIFF_VIEWER_THEME = {
- "--diffs-light-bg": "oklch(0.985 0.002 247)",
- "--diffs-dark-bg": "oklch(0.18 0.003 247)",
- "--diffs-light": "oklch(0.22 0.01 247)",
- "--diffs-dark": "oklch(0.92 0.006 247)",
- "--diffs-bg-context-override":
- "light-dark(oklch(0.967 0.003 247), oklch(0.235 0.004 247))",
- "--diffs-bg-context-gutter-override":
- "light-dark(oklch(0.948 0.004 247), oklch(0.205 0.004 247))",
- "--diffs-bg-separator-override":
- "light-dark(oklch(0.94 0.004 247), oklch(0.255 0.005 247))",
- "--diffs-bg-buffer-override":
- "light-dark(oklch(0.955 0.004 247), oklch(0.225 0.004 247))",
- "--diffs-light-addition-color": "oklch(0.54 0.13 158)",
- "--diffs-dark-addition-color": "oklch(0.72 0.13 158)",
- "--diffs-light-deletion-color": "oklch(0.55 0.16 28)",
- "--diffs-dark-deletion-color": "oklch(0.72 0.14 28)",
- "--diffs-bg-addition-override":
- "light-dark(oklch(0.957 0.032 158), oklch(0.255 0.052 158))",
- "--diffs-bg-addition-emphasis-override":
- "light-dark(oklch(0.88 0.06 158), oklch(0.36 0.08 158))",
- "--diffs-bg-deletion-override":
- "light-dark(oklch(0.958 0.03 28), oklch(0.255 0.047 28))",
- "--diffs-bg-deletion-emphasis-override":
- "light-dark(oklch(0.9 0.052 28), oklch(0.36 0.075 28))",
- "--diffs-fg-number-override":
- "light-dark(oklch(0.56 0.018 247), oklch(0.66 0.012 247))",
- "--diffs-font-size": "12px",
- "--diffs-line-height": "20px",
-} as React.CSSProperties
function readIsDarkTheme() {
return (
@@ -2053,13 +2023,12 @@ export function JsonDiffView({
return (
<Virtualizer
- className="h-full overflow-auto rounded-b-xl bg-surface/60"
+ className="h-full overflow-auto bg-surface/60"
contentClassName="min-w-full"
>
<div className="human-review-diff h-full text-xs">
<MultiFileDiff
className="block min-w-full"
- style={DIFF_VIEWER_THEME}
oldFile={oldFile}
newFile={newFile}
options={{
diff --git a/apps/v4/registry/new-york-v4/ui/schema-builder.tsx b/apps/v4/registry/new-york-v4/ui/schema-builder.tsx
new file mode 100644
index 0000000..2cb31f1
--- /dev/null
+++ b/apps/v4/registry/new-york-v4/ui/schema-builder.tsx
@@ -0,0 +1,2392 @@
+"use client"
+
+import * as React from "react"
+import {
+ closestCenter,
+ DndContext,
+ DragOverlay,
+ getFirstCollision,
+ KeyboardSensor,
+ MeasuringStrategy,
+ PointerSensor,
+ pointerWithin,
+ rectIntersection,
+ useDroppable,
+ useSensor,
+ useSensors,
+ type CollisionDetection,
+ type DragEndEvent,
+ type DragOverEvent,
+ type DragStartEvent,
+ type UniqueIdentifier,
+} from "@dnd-kit/core"
+import {
+ arrayMove,
+ SortableContext,
+ sortableKeyboardCoordinates,
+ useSortable,
+ verticalListSortingStrategy,
+} from "@dnd-kit/sortable"
+import { CSS } from "@dnd-kit/utilities"
+import {
+ Add01Icon,
+ CancelCircleIcon,
+ ChevronDown,
+ DragDropVerticalIcon,
+ InputNumericIcon,
+ InputTextIcon,
+ LeftToRightListBulletIcon,
+ SecondBracketIcon,
+ SourceCodeSquareIcon,
+ TableIcon,
+ TextCheckIcon,
+} from "@hugeicons/core-free-icons"
+import { HugeiconsIcon } from "@hugeicons/react"
+import {
+ File,
+ Virtualizer,
+ WorkerPoolContextProvider,
+ type VirtualFileMetrics,
+ type WorkerInitializationRenderOptions,
+ type WorkerPoolOptions,
+} from "@pierre/diffs/react"
+import { useTheme } from "next-themes"
+
+import { cn } from "@/lib/utils"
+import { Button } from "@/registry/new-york-v4/ui/button"
+import {
+ Collapsible,
+ CollapsiblePanel,
+ CollapsibleTrigger,
+} from "@/registry/new-york-v4/ui/collapsible"
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@/registry/new-york-v4/ui/dropdown-menu"
+import { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"
+import {
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+} from "@/registry/new-york-v4/ui/tabs"
+
+export type SchemaBuilderScalarType =
+ | "string"
+ | "number"
+ | "integer"
+ | "boolean"
+ | "null"
+export type SchemaBuilderFieldType =
+ | SchemaBuilderScalarType
+ | "object"
+ | "array"
+ | "enum"
+export type SchemaBuilderArrayScalarType = Exclude<
+ SchemaBuilderScalarType,
+ "null"
+>
+export type SchemaBuilderArrayItemType =
+ | SchemaBuilderArrayScalarType
+ | "object"
+ | "enum"
+
+export type SchemaBuilderEnumValue = {
+ id: string
+ value: string
+ description: string
+}
+
+export type SchemaBuilderProperty = {
+ id: string
+ key: string
+ type: SchemaBuilderFieldType
+ description: string
+ enumValues?: SchemaBuilderEnumValue[]
+ properties?: SchemaBuilderProperty[]
+ items?: {
+ type: SchemaBuilderArrayItemType
+ properties?: SchemaBuilderProperty[]
+ enumValues?: SchemaBuilderEnumValue[]
+ }
+}
+
+export type SchemaBuilderSchema = {
+ properties: SchemaBuilderProperty[]
+}
+
+export type SchemaBuilderTheme = "light" | "dark"
+
+export type SerializedSchemaProperty = {
+ type: string
+ description?: string
+ enum?: string[]
+ enumDescriptions?: Record<string, string>
+ properties?: Record<string, SerializedSchemaProperty>
+ items?: SerializedSchemaProperty
+}
+
+export type SerializedSchema = {
+ type: "object"
+ properties: Record<string, SerializedSchemaProperty>
+}
+
+const SCALAR_TYPES: SchemaBuilderScalarType[] = [
+ "string",
+ "number",
+ "integer",
+ "boolean",
+ "null",
+]
+const ARRAY_SCALAR_TYPES: SchemaBuilderArrayScalarType[] = [
+ "string",
+ "number",
+ "integer",
+ "boolean",
+]
+const ROOT_SCHEMA_CONTAINER_ID = "schema-root"
+const SCHEMA_PROPERTY_DRAG_TYPE = "schema-property"
+const ENUM_VALUE_DRAG_TYPE = "enum-value"
+const PROPERTY_REORDER_EDGE_THRESHOLD_PX = 18
+const SCHEMA_DND_MEASURING = {
+ droppable: {
+ strategy: MeasuringStrategy.WhileDragging,
+ },
+}
+
+function getDroppableRectArea(
+ droppableRects: Parameters<CollisionDetection>[0]["droppableRects"],
+ id: UniqueIdentifier
+) {
+ const rect = droppableRects.get(id)
+ return rect ? rect.width * rect.height : Number.POSITIVE_INFINITY
+}
+
+function getProjectedPropertyChildContainerId(
+ properties: SchemaBuilderProperty[],
+ propertyId: UniqueIdentifier,
+ args: Parameters<CollisionDetection>[0]
+) {
+ const overLocation = findPropertyLocation(properties, String(propertyId))
+ const childContainerId = overLocation
+ ? getPropertyChildContainerId(overLocation.property)
+ : null
+ const overRect = args.droppableRects.get(propertyId)
+
+ if (
+ childContainerId &&
+ args.pointerCoordinates &&
+ overRect &&
+ args.pointerCoordinates.x > overRect.left + overRect.width * 0.18
+ ) {
+ return childContainerId
+ }
+
+ return null
+}
+
+const TYPE_LABELS: Record<
+ SchemaBuilderFieldType | `array-${SchemaBuilderArrayItemType}`,
+ string
+> = {
+ string: "String",
+ number: "Number",
+ integer: "Integer",
+ boolean: "Boolean",
+ null: "Null",
+ object: "Object",
+ array: "Array",
+ enum: "Enum",
+ "array-string": "Array<string>",
+ "array-number": "Array<number>",
+ "array-integer": "Array<integer>",
+ "array-boolean": "Array<boolean>",
+ "array-enum": "Array<enum>",
+ "array-object": "Array<object>",
+}
+
+type SchemaBuilderTypeStyleKey =
+ | SchemaBuilderFieldType
+ | `array-${SchemaBuilderArrayItemType}`
+
+const TYPE_STYLES: Record<
+ SchemaBuilderTypeStyleKey,
+ {
+ icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]
+ badge: string
+ }
+> = {
+ string: {
+ icon: InputTextIcon,
+ badge: "bg-blue-50 text-blue-600 dark:bg-blue-300/10 dark:text-blue-300",
+ },
+ number: {
+ icon: InputNumericIcon,
+ badge:
+ "bg-emerald-50 text-emerald-600 dark:bg-emerald-300/10 dark:text-emerald-300",
+ },
+ integer: {
+ icon: InputNumericIcon,
+ badge: "bg-teal-50 text-teal-600 dark:bg-teal-300/10 dark:text-teal-300",
+ },
+ boolean: {
+ icon: TextCheckIcon,
+ badge:
+ "bg-amber-50 text-amber-600 dark:bg-amber-300/10 dark:text-amber-300",
+ },
+ null: {
+ icon: CancelCircleIcon,
+ badge: "bg-zinc-50 text-zinc-600 dark:bg-zinc-300/10 dark:text-zinc-300",
+ },
+ object: {
+ icon: SourceCodeSquareIcon,
+ badge:
+ "bg-violet-50 text-violet-600 dark:bg-violet-300/10 dark:text-violet-300",
+ },
+ array: {
+ icon: SecondBracketIcon,
+ badge: "bg-cyan-50 text-cyan-600 dark:bg-cyan-300/10 dark:text-cyan-300",
+ },
+ enum: {
+ icon: LeftToRightListBulletIcon,
+ badge: "bg-rose-50 text-rose-600 dark:bg-rose-300/10 dark:text-rose-300",
+ },
+ "array-string": {
+ icon: SecondBracketIcon,
+ badge: "bg-blue-50 text-blue-600 dark:bg-blue-300/10 dark:text-blue-300",
+ },
+ "array-number": {
+ icon: SecondBracketIcon,
+ badge:
+ "bg-emerald-50 text-emerald-600 dark:bg-emerald-300/10 dark:text-emerald-300",
+ },
+ "array-integer": {
+ icon: SecondBracketIcon,
+ badge: "bg-teal-50 text-teal-600 dark:bg-teal-300/10 dark:text-teal-300",
+ },
+ "array-boolean": {
+ icon: SecondBracketIcon,
+ badge:
+ "bg-amber-50 text-amber-600 dark:bg-amber-300/10 dark:text-amber-300",
+ },
+ "array-enum": {
+ icon: LeftToRightListBulletIcon,
+ badge: "bg-rose-50 text-rose-600 dark:bg-rose-300/10 dark:text-rose-300",
+ },
+ "array-object": {
+ icon: SecondBracketIcon,
+ badge:
+ "bg-violet-50 text-violet-600 dark:bg-violet-300/10 dark:text-violet-300",
+ },
+}
+
+const CODE_FILE_THEME = {
+ "--diffs-light-bg": "var(--color-code)",
+ "--diffs-dark-bg": "var(--color-code)",
+ "--diffs-light": "var(--color-code-foreground)",
+ "--diffs-dark": "var(--color-code-foreground)",
+ "--diffs-bg-context-override": "var(--color-code)",
+ "--diffs-bg-context-gutter-override": "var(--color-code)",
+ "--diffs-bg-buffer-override": "var(--color-code)",
+ "--diffs-fg-number-override": "var(--color-muted-foreground)",
+ "--diffs-font-size": "0.8rem",
+ "--diffs-line-height": "1.625",
+} as React.CSSProperties
+
+const CODE_FONT_SIZE_PX = 12.8
+const CODE_LINE_HEIGHT_PX = CODE_FONT_SIZE_PX * 1.625
+
+const CODE_VIRTUAL_FILE_METRICS = {
+ hunkLineCount: 50,
+ lineHeight: CODE_LINE_HEIGHT_PX,
+ diffHeaderHeight: 44,
+ spacing: 8,
+ paddingTop: 0,
+ paddingBottom: 8,
+} satisfies VirtualFileMetrics
+
+const CODE_HIGHLIGHTER_OPTIONS = {
+ theme: {
+ light: "pierre-light-soft",
+ dark: "pierre-dark-soft",
+ },
+ langs: ["json"],
+} satisfies WorkerInitializationRenderOptions
+
+const CODE_WORKER_POOL_OPTIONS = {
+ workerFactory: () =>
+ new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), {
+ type: "module",
+ }),
+} satisfies WorkerPoolOptions
+
+function useResolvedCodeThemeType(theme?: SchemaBuilderTheme) {
+ const { resolvedTheme } = useTheme()
+ const [isMounted, setIsMounted] = React.useState(false)
+
+ React.useEffect(() => {
+ setIsMounted(true)
+ }, [])
+
+ if (theme) return theme
+
+ return isMounted && resolvedTheme === "dark" ? "dark" : "light"
+}
+
+export const SAMPLE_SCHEMA: SchemaBuilderSchema = {
+ properties: [
+ {
+ id: "statement-period",
+ key: "statement_period",
+ type: "string",
+ description: "Date range covered by the bank statement.",
+ },
+ {
+ id: "account-type",
+ key: "account_type",
+ type: "enum",
+ description: "Account product shown on the statement.",
+ enumValues: [
+ {
+ id: "account-type-checking",
+ value: "checking",
+ description: "Standard checking account.",
+ },
+ {
+ id: "account-type-savings",
+ value: "savings",
+ description: "Savings or money market account.",
+ },
+ ],
+ },
+ {
+ id: "account-holder",
+ key: "account_holder",
+ type: "object",
+ description: "Person or business that owns the account.",
+ properties: [
+ {
+ id: "holder-name",
+ key: "name",
+ type: "string",
+ description: "Full account holder name.",
+ },
+ {
+ id: "holder-address",
+ key: "address",
+ type: "object",
+ description: "Mailing address for the account holder.",
+ properties: [
+ {
+ id: "holder-address-line-1",
+ key: "line_1",
+ type: "string",
+ description: "Street address line.",
+ },
+ {
+ id: "holder-address-city",
+ key: "city",
+ type: "string",
+ description: "City from the mailing address.",
+ },
+ ],
+ },
+ ],
+ },
+ {
+ id: "transactions",
+ key: "transactions",
+ type: "array",
+ description: "Posted account activity during the statement period.",
+ items: {
+ type: "object",
+ properties: [
+ {
+ id: "transaction-date",
+ key: "date",
+ type: "string",
+ description: "Posting date for the transaction.",
+ },
+ {
+ id: "transaction-description",
+ key: "description",
+ type: "string",
+ description: "Statement transaction description.",
+ },
+ {
+ id: "transaction-amount",
+ key: "amount",
+ type: "number",
+ description: "Signed transaction amount.",
+ },
+ ],
+ },
+ },
+ ],
+}
+
+let nextPropertyId = 0
+
+function createId(prefix: string) {
+ nextPropertyId += 1
+ return `${prefix}-${nextPropertyId}`
+}
+
+function createEnumValue(): SchemaBuilderEnumValue {
+ return {
+ id: createId("enum"),
+ value: "",
+ description: "",
+ }
+}
+
+function createProperty(
+ type: SchemaBuilderFieldType = "string"
+): SchemaBuilderProperty {
+ return normalizePropertyForType({
+ id: createId("property"),
+ key: "",
+ type,
+ description: "",
+ })
+}
+
+function normalizePropertyForType(
+ property: SchemaBuilderProperty,
+ type = property.type
+): SchemaBuilderProperty {
+ const base = {
+ ...property,
+ type,
+ }
+
+ if (type === "enum") {
+ return {
+ ...base,
+ enumValues: base.enumValues?.length
+ ? base.enumValues
+ : [createEnumValue()],
+ properties: undefined,
+ items: undefined,
+ }
+ }
+
+ if (type === "object") {
+ return {
+ ...base,
+ enumValues: undefined,
+ properties: base.properties?.length
+ ? base.properties
+ : [createProperty("string")],
+ items: undefined,
+ }
+ }
+
+ if (type === "array") {
+ return {
+ ...base,
+ enumValues: undefined,
+ properties: undefined,
+ items: base.items ?? {
+ type: "object",
+ properties: [createProperty("string")],
+ },
+ }
+ }
+
+ return {
+ ...base,
+ enumValues: undefined,
+ properties: undefined,
+ items: undefined,
+ }
+}
+
+function formatJson(value: unknown) {
+ return JSON.stringify(value, null, 2)
+}
+
+function serializeProperty(
+ property: SchemaBuilderProperty
+): SerializedSchemaProperty {
+ const description = property.description.trim()
+ const base = description ? { description } : {}
+
+ if (property.type === "enum") {
+ const enumValues = property.enumValues ?? []
+ return {
+ type: "string",
+ ...base,
+ enum: enumValues.map((option) => option.value),
+ enumDescriptions: Object.fromEntries(
+ enumValues
+ .filter((option) => option.description.trim())
+ .map((option) => [option.value, option.description])
+ ),
+ }
+ }
+
+ if (property.type === "object") {
+ return {
+ type: "object",
+ ...base,
+ properties: serializeProperties(property.properties ?? []),
+ }
+ }
+
+ if (property.type === "array") {
+ const items = property.items ?? { type: "string" as const }
+
+ return {
+ type: "array",
+ ...base,
+ items:
+ items.type === "object"
+ ? {
+ type: "object",
+ properties: serializeProperties(items.properties ?? []),
+ }
+ : items.type === "enum"
+ ? {
+ type: "string",
+ enum: (items.enumValues ?? []).map((option) => option.value),
+ enumDescriptions: Object.fromEntries(
+ (items.enumValues ?? [])
+ .filter((option) => option.description.trim())
+ .map((option) => [option.value, option.description])
+ ),
+ }
+ : { type: items.type },
+ }
+ }
+
+ return {
+ type: property.type,
+ ...base,
+ }
+}
+
+function serializeProperties(
+ properties: SchemaBuilderProperty[]
+): Record<string, SerializedSchemaProperty> {
+ return Object.fromEntries(
+ properties
+ .filter((property) => property.key.trim())
+ .map((property) => [property.key.trim(), serializeProperty(property)])
+ )
+}
+
+export function serializeSchema(schema: SchemaBuilderSchema): SerializedSchema {
+ return {
+ type: "object",
+ properties: serializeProperties(schema.properties),
+ }
+}
+
+function updatePropertyById(
+ properties: SchemaBuilderProperty[],
+ id: string,
+ update: (property: SchemaBuilderProperty) => SchemaBuilderProperty
+) {
+ return properties.map((property) =>
+ property.id === id ? update(property) : property
+ )
+}
+
+function getObjectContainerId(propertyId: string) {
+ return `object:${propertyId}`
+}
+
+function getArrayObjectContainerId(propertyId: string) {
+ return `array-object:${propertyId}`
+}
+
+function isPropertyContainerId(id: UniqueIdentifier) {
+ const value = String(id)
+
+ return (
+ value === ROOT_SCHEMA_CONTAINER_ID ||
+ value.startsWith("object:") ||
+ value.startsWith("array-object:")
+ )
+}
+
+function getPropertyChildContainerId(property: SchemaBuilderProperty) {
+ if (property.type === "object") {
+ return getObjectContainerId(property.id)
+ }
+
+ if (property.type === "array" && property.items?.type === "object") {
+ return getArrayObjectContainerId(property.id)
+ }
+
+ return null
+}
+
+function propertyHasNestedEditor(property: SchemaBuilderProperty) {
+ return (
+ property.type === "enum" ||
+ property.type === "object" ||
+ property.type === "array"
+ )
+}
+
+function getNestedEditorLabel(property: SchemaBuilderProperty) {
+ return `${
+ property.type === "enum" ? "Configure enums" : "Configure schema"
+ } for ${property.key || "property"}`
+}
+
+type PropertyLocation = {
+ containerId: string
+ index: number
+ property: SchemaBuilderProperty
+}
+
+const NOT_FOUND_PROPERTIES: SchemaBuilderProperty[] = []
+
+function findPropertyLocation(
+ properties: SchemaBuilderProperty[],
+ propertyId: string,
+ containerId = ROOT_SCHEMA_CONTAINER_ID
+): PropertyLocation | null {
+ for (let index = 0; index < properties.length; index += 1) {
+ const property = properties[index]
+ if (!property) continue
+
+ if (property.id === propertyId) {
+ return {
+ containerId,
+ index,
+ property,
+ }
+ }
+
+ if (property.type === "object") {
+ const nestedLocation = findPropertyLocation(
+ property.properties ?? [],
+ propertyId,
+ getObjectContainerId(property.id)
+ )
+ if (nestedLocation) return nestedLocation
+ }
+
+ if (property.type === "array" && property.items?.type === "object") {
+ const nestedLocation = findPropertyLocation(
+ property.items.properties ?? [],
+ propertyId,
+ getArrayObjectContainerId(property.id)
+ )
+ if (nestedLocation) return nestedLocation
+ }
+ }
+
+ return null
+}
+
+function propertyOwnsContainer(
+ property: SchemaBuilderProperty,
+ containerId: string
+): boolean {
+ if (property.type === "object") {
+ if (getObjectContainerId(property.id) === containerId) return true
+
+ if (
+ (property.properties ?? []).some((childProperty) =>
+ propertyOwnsContainer(childProperty, containerId)
+ )
+ ) {
+ return true
+ }
+ }
+
+ if (property.type === "array" && property.items?.type === "object") {
+ if (getArrayObjectContainerId(property.id) === containerId) return true
+
+ return (property.items.properties ?? []).some((childProperty) =>
+ propertyOwnsContainer(childProperty, containerId)
+ )
+ }
+
+ return false
+}
+
+function getContainerProperties(
+ properties: SchemaBuilderProperty[],
+ containerId: string
+): SchemaBuilderProperty[] {
+ if (containerId === ROOT_SCHEMA_CONTAINER_ID) return properties
+
+ for (const property of properties) {
+ if (property.type === "object") {
+ if (getObjectContainerId(property.id) === containerId) {
+ return property.properties ?? []
+ }
+
+ const nestedProperties = getContainerProperties(
+ property.properties ?? [],
+ containerId
+ )
+ if (nestedProperties !== NOT_FOUND_PROPERTIES) return nestedProperties
+ }
+
+ if (property.type === "array" && property.items?.type === "object") {
+ if (getArrayObjectContainerId(property.id) === containerId) {
+ return property.items.properties ?? []
+ }
+
+ const nestedProperties = getContainerProperties(
+ property.items.properties ?? [],
+ containerId
+ )
+ if (nestedProperties !== NOT_FOUND_PROPERTIES) return nestedProperties
+ }
+ }
+
+ return NOT_FOUND_PROPERTIES
+}
+
+function setContainerProperties(
+ properties: SchemaBuilderProperty[],
+ containerId: string,
+ nextContainerProperties: SchemaBuilderProperty[]
+): SchemaBuilderProperty[] {
+ if (containerId === ROOT_SCHEMA_CONTAINER_ID) return nextContainerProperties
+
+ return properties.map((property) => {
+ if (property.type === "object") {
+ if (getObjectContainerId(property.id) === containerId) {
+ return {
+ ...property,
+ properties: nextContainerProperties,
+ }
+ }
+
+ return {
+ ...property,
+ properties: setContainerProperties(
+ property.properties ?? [],
+ containerId,
+ nextContainerProperties
+ ),
+ }
+ }
+
+ if (property.type === "array" && property.items?.type === "object") {
+ if (getArrayObjectContainerId(property.id) === containerId) {
+ return {
+ ...property,
+ items: {
+ ...property.items,
+ properties: nextContainerProperties,
+ },
+ }
+ }
+
+ return {
+ ...property,
+ items: {
+ ...property.items,
+ properties: setContainerProperties(
+ property.items.properties ?? [],
+ containerId,
+ nextContainerProperties
+ ),
+ },
+ }
+ }
+
+ return property
+ })
+}
+
+function moveProperty(
+ properties: SchemaBuilderProperty[],
+ activeId: string,
+ overId: string
+) {
+ const activeLocation = findPropertyLocation(properties, activeId)
+ if (!activeLocation) return properties
+
+ const overLocation = findPropertyLocation(properties, overId)
+ const targetContainerId = overLocation?.containerId ?? overId
+ if (!isPropertyContainerId(targetContainerId)) return properties
+
+ if (propertyOwnsContainer(activeLocation.property, targetContainerId)) {
+ return properties
+ }
+
+ if (activeLocation.containerId === targetContainerId) {
+ if (!overLocation) return properties
+
+ const containerProperties = getContainerProperties(
+ properties,
+ activeLocation.containerId
+ )
+ const targetIndex = overLocation.index
+
+ if (activeLocation.index === targetIndex) return properties
+
+ return setContainerProperties(
+ properties,
+ activeLocation.containerId,
+ arrayMove(containerProperties, activeLocation.index, targetIndex)
+ )
+ }
+
+ const sourceProperties = getContainerProperties(
+ properties,
+ activeLocation.containerId
+ )
+ let nextProperties = setContainerProperties(
+ properties,
+ activeLocation.containerId,
+ sourceProperties.filter((property) => property.id !== activeId)
+ )
+ const refreshedOverLocation = overLocation
+ ? findPropertyLocation(nextProperties, overId)
+ : null
+ const targetProperties = getContainerProperties(
+ nextProperties,
+ targetContainerId
+ )
+ const targetIndex = refreshedOverLocation?.index ?? targetProperties.length
+ const nextTargetProperties = targetProperties.slice()
+
+ nextTargetProperties.splice(targetIndex, 0, activeLocation.property)
+ nextProperties = setContainerProperties(
+ nextProperties,
+ targetContainerId,
+ nextTargetProperties
+ )
+
+ return nextProperties
+}
+
+type PropertyMovePreview = {
+ containerId: string
+ index: number
+ property: SchemaBuilderProperty
+}
+
+function getPropertyMovePreview(
+ properties: SchemaBuilderProperty[],
+ activeId: string,
+ overId: string
+): PropertyMovePreview | null {
+ const activeLocation = findPropertyLocation(properties, activeId)
+ if (!activeLocation) return null
+
+ const overLocation = findPropertyLocation(properties, overId)
+ const targetContainerId = overLocation?.containerId ?? overId
+ if (!isPropertyContainerId(targetContainerId)) return null
+
+ if (propertyOwnsContainer(activeLocation.property, targetContainerId)) {
+ return null
+ }
+
+ if (activeLocation.containerId === targetContainerId) return null
+
+ const targetProperties = getContainerProperties(properties, targetContainerId)
+
+ return {
+ containerId: targetContainerId,
+ index: overLocation?.index ?? targetProperties.length,
+ property: activeLocation.property,
+ }
+}
+
+function isSameContainerPropertyReorderReady(
+ properties: SchemaBuilderProperty[],
+ activeId: UniqueIdentifier,
+ overId: UniqueIdentifier,
+ args: Parameters<CollisionDetection>[0]
+) {
+ const activeLocation = findPropertyLocation(properties, String(activeId))
+ const overLocation = findPropertyLocation(properties, String(overId))
+ if (!activeLocation || !overLocation) return true
+ if (activeLocation.containerId !== overLocation.containerId) return true
+
+ const overRect = args.droppableRects.get(overId)
+ if (!overRect || !args.pointerCoordinates) return true
+
+ const threshold = Math.min(
+ PROPERTY_REORDER_EDGE_THRESHOLD_PX,
+ overRect.height / 2
+ )
+
+ if (activeLocation.index < overLocation.index) {
+ return args.pointerCoordinates.y >= overRect.bottom - threshold
+ }
+
+ if (activeLocation.index > overLocation.index) {
+ return args.pointerCoordinates.y <= overRect.top + threshold
+ }
+
+ return false
+}
+
+function isSchemaCollisionCandidate(
+ properties: SchemaBuilderProperty[],
+ id: UniqueIdentifier,
+ activeId: UniqueIdentifier,
+ args: Parameters<CollisionDetection>[0]
+) {
+ if (id === activeId) return false
+
+ const value = String(id)
+ const isSchemaTarget =
+ isPropertyContainerId(value) ||
+ Boolean(findPropertyLocation(properties, value))
+
+ return (
+ isSchemaTarget &&
+ isSameContainerPropertyReorderReady(properties, activeId, id, args)
+ )
+}
+
+function isPointerBelowLastContainerProperty(
+ containerProperties: SchemaBuilderProperty[],
+ args: Parameters<CollisionDetection>[0]
+) {
+ const lastProperty = containerProperties.at(-1)
+ if (!lastProperty || !args.pointerCoordinates) return true
+
+ const lastPropertyRect = args.droppableRects.get(lastProperty.id)
+ if (!lastPropertyRect) return false
+
+ return args.pointerCoordinates.y >= lastPropertyRect.bottom
+}
+
+function useSchemaBuilderSensors() {
+ return useSensors(
+ useSensor(PointerSensor, {
+ activationConstraint: {
+ distance: 6,
+ },
+ }),
+ useSensor(KeyboardSensor, {
+ coordinateGetter: sortableKeyboardCoordinates,
+ })
+ )
+}
+
+function getTypeStyleKey(
+ property: SchemaBuilderProperty
+): SchemaBuilderTypeStyleKey {
+ if (property.type === "array" && property.items) {
+ return `array-${property.items.type}`
+ }
+
+ return property.type
+}
+
+function SchemaTypeBadge({
+ className,
+ type,
+}: {
+ className?: string
+ type: SchemaBuilderTypeStyleKey
+}) {
+ const style = TYPE_STYLES[type]
+
+ return (
+ <span
+ className={cn(
+ "inline-flex min-w-0 shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium",
+ style.badge,
+ className
+ )}
+ >
+ <HugeiconsIcon icon={style.icon} className="size-3.5" />
+ <span className="truncate">{TYPE_LABELS[type]}</span>
+ </span>
+ )
+}
+
+function SchemaTypeMenuItem({
+ type,
+ onSelect,
+}: {
+ type: SchemaBuilderTypeStyleKey
+ onSelect: () => void
+}) {
+ return (
+ <DropdownMenuItem onClick={onSelect}>
+ <SchemaTypeBadge type={type} />
+ </DropdownMenuItem>
+ )
+}
+
+function SchemaTypeMenu({
+ property,
+ onChange,
+}: {
+ property: SchemaBuilderProperty
+ onChange: (property: SchemaBuilderProperty) => void
+}) {
+ const updateType = React.useCallback(
+ (type: SchemaBuilderFieldType) => {
+ onChange(normalizePropertyForType(property, type))
+ },
+ [onChange, property]
+ )
+
+ const updateArrayItemType = React.useCallback(
+ (itemType: SchemaBuilderArrayItemType) => {
+ onChange({
+ ...normalizePropertyForType(property, "array"),
+ items:
+ itemType === "object"
+ ? {
+ type: "object",
+ properties: property.items?.properties?.length
+ ? property.items.properties
+ : [createProperty("string")],
+ }
+ : itemType === "enum"
+ ? {
+ type: "enum",
+ enumValues: property.items?.enumValues?.length
+ ? property.items.enumValues
+ : [createEnumValue()],
+ }
+ : { type: itemType },
+ })
+ },
+ [onChange, property]
+ )
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-8 w-full justify-between rounded-md px-2"
+ >
+ <SchemaTypeBadge type={getTypeStyleKey(property)} />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-44">
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>JSON types</DropdownMenuLabel>
+ {SCALAR_TYPES.map((type) => (
+ <SchemaTypeMenuItem
+ key={type}
+ type={type}
+ onSelect={() => updateType(type)}
+ />
+ ))}
+ <SchemaTypeMenuItem type="enum" onSelect={() => updateType("enum")} />
+ <SchemaTypeMenuItem
+ type="object"
+ onSelect={() => updateType("object")}
+ />
+ </DropdownMenuGroup>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <SchemaTypeBadge type="array" />
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-44">
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>Nested</DropdownMenuLabel>
+ <SchemaTypeMenuItem
+ type="array-object"
+ onSelect={() => updateArrayItemType("object")}
+ />
+ <SchemaTypeMenuItem
+ type="array-enum"
+ onSelect={() => updateArrayItemType("enum")}
+ />
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>Scalars</DropdownMenuLabel>
+ {ARRAY_SCALAR_TYPES.map((type) => (
+ <SchemaTypeMenuItem
+ key={type}
+ type={`array-${type}`}
+ onSelect={() => updateArrayItemType(type)}
+ />
+ ))}
+ </DropdownMenuGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
+
+function ArrayItemTypeMenu({
+ property,
+ onChange,
+}: {
+ property: SchemaBuilderProperty
+ onChange: (property: SchemaBuilderProperty) => void
+}) {
+ const items = property.items ?? { type: "string" as const }
+
+ const updateItemType = React.useCallback(
+ (type: SchemaBuilderArrayItemType) => {
+ onChange({
+ ...property,
+ items:
+ type === "object"
+ ? {
+ type: "object",
+ properties: items.properties?.length
+ ? items.properties
+ : [createProperty("string")],
+ }
+ : type === "enum"
+ ? {
+ type: "enum",
+ enumValues: items.enumValues?.length
+ ? items.enumValues
+ : [createEnumValue()],
+ }
+ : { type },
+ })
+ },
+ [items.enumValues, items.properties, onChange, property]
+ )
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-6 px-2"
+ onClick={(event) => event.stopPropagation()}
+ onPointerDown={(event) => event.stopPropagation()}
+ >
+ <SchemaTypeBadge type={`array-${items.type}`} />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>Nested</DropdownMenuLabel>
+ <SchemaTypeMenuItem
+ type="array-object"
+ onSelect={() => updateItemType("object")}
+ />
+ <SchemaTypeMenuItem
+ type="array-enum"
+ onSelect={() => updateItemType("enum")}
+ />
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>Scalars</DropdownMenuLabel>
+ {ARRAY_SCALAR_TYPES.map((type) => (
+ <SchemaTypeMenuItem
+ key={type}
+ type={`array-${type}`}
+ onSelect={() => updateItemType(type)}
+ />
+ ))}
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
+
+function InlineTextInput({
+ className,
+ onChange,
+ onInput,
+ ...props
+}: React.InputHTMLAttributes<HTMLInputElement>) {
+ const handleInput = React.useCallback(
+ (event: React.FormEvent<HTMLInputElement>) => {
+ onInput?.(event)
+ onChange?.(event as unknown as React.ChangeEvent<HTMLInputElement>)
+ },
+ [onChange, onInput]
+ )
+
+ return (
+ <input
+ className={cn(
+ "h-9 w-full min-w-0 bg-transparent px-3 text-sm outline-none placeholder:text-muted-foreground/60 focus:bg-background",
+ className
+ )}
+ onInput={handleInput}
+ {...props}
+ />
+ )
+}
+
+function EnumEditor({
+ values,
+ onChange,
+}: {
+ values: SchemaBuilderEnumValue[]
+ onChange: (values: SchemaBuilderEnumValue[]) => void
+}) {
+ const sensors = useSchemaBuilderSensors()
+ const dndContextId = React.useId()
+ const sortableItems = React.useMemo(
+ () => values.map((value) => value.id),
+ [values]
+ )
+ const updateValue = React.useCallback(
+ (
+ id: string,
+ update: (value: SchemaBuilderEnumValue) => SchemaBuilderEnumValue
+ ) => {
+ onChange(values.map((value) => (value.id === id ? update(value) : value)))
+ },
+ [onChange, values]
+ )
+ const handleDragEnd = React.useCallback(
+ (event: DragEndEvent) => {
+ const { active, over } = event
+ if (!over || active.id === over.id) return
+
+ const activeIndex = values.findIndex((value) => value.id === active.id)
+ const overIndex = values.findIndex((value) => value.id === over.id)
+
+ if (activeIndex < 0 || overIndex < 0) return
+
+ onChange(arrayMove(values, activeIndex, overIndex))
+ },
+ [onChange, values]
+ )
+
+ return (
+ <DndContext
+ id={`schema-builder-enum-${dndContextId}`}
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={handleDragEnd}
+ >
+ <div className="overflow-visible rounded-lg border bg-background">
+ <table className="w-full table-fixed border-collapse text-sm">
+ <thead>
+ <tr className="border-b bg-muted/55 text-xs text-muted-foreground">
+ <th className="w-[34%] px-3 py-2 text-left font-medium">Value</th>
+ <th className="border-l px-3 py-2 text-left font-medium">
+ Description
+ </th>
+ </tr>
+ </thead>
+ <SortableContext
+ id={`schema-builder-enum-sortable-${dndContextId}`}
+ items={sortableItems}
+ strategy={verticalListSortingStrategy}
+ >
+ <tbody>
+ {values.map((value) => (
+ <SortableEnumRow
+ key={value.id}
+ value={value}
+ onValueChange={updateValue}
+ />
+ ))}
+ <tr>
+ <td colSpan={2} className="p-0">
+ <button
+ type="button"
+ className="flex h-9 w-full items-center justify-center gap-2 text-sm text-muted-foreground transition-colors outline-none hover:bg-muted/55 hover:text-foreground focus-visible:bg-muted/55 focus-visible:text-foreground"
+ onClick={() => onChange([...values, createEnumValue()])}
+ >
+ <HugeiconsIcon icon={Add01Icon} className="size-4" />
+ Add enum value
+ </button>
+ </td>
+ </tr>
+ </tbody>
+ </SortableContext>
+ </table>
+ </div>
+ </DndContext>
+ )
+}
+
+function SortableEnumRow({
+ value,
+ onValueChange,
+}: {
+ value: SchemaBuilderEnumValue
+ onValueChange: (
+ id: string,
+ update: (value: SchemaBuilderEnumValue) => SchemaBuilderEnumValue
+ ) => void
+}) {
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({
+ id: value.id,
+ data: {
+ type: ENUM_VALUE_DRAG_TYPE,
+ },
+ })
+
+ return (
+ <tr
+ ref={setNodeRef}
+ className={cn(
+ "group/enum-row border-b",
+ isDragging && "relative z-10 opacity-70"
+ )}
+ style={{
+ transform: CSS.Translate.toString(transform),
+ transition,
+ }}
+ >
+ <td className="relative p-0 align-top">
+ <button
+ type="button"
+ className={cn(
+ "absolute top-1/2 left-0 z-50 grid size-5 -translate-x-1/2 -translate-y-1/2 cursor-grab place-items-center rounded-md border bg-background text-muted-foreground opacity-0 shadow-sm transition-[opacity,color,box-shadow] outline-none group-hover/enum-row:opacity-100 hover:text-foreground focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing",
+ isDragging && "opacity-100"
+ )}
+ aria-label={`Drag enum value ${value.value || "empty value"}`}
+ {...attributes}
+ {...listeners}
+ >
+ <HugeiconsIcon icon={DragDropVerticalIcon} className="size-3.5" />
+ </button>
+ <div className="min-w-0">
+ <InlineTextInput
+ value={value.value}
+ placeholder="approved"
+ onChange={(event) =>
+ onValueChange(value.id, (current) => ({
+ ...current,
+ value: event.target.value,
+ }))
+ }
+ />
+ </div>
+ </td>
+ <td className="border-l p-0 align-top">
+ <InlineTextInput
+ value={value.description}
+ placeholder="When the reviewer accepts the extracted value."
+ onChange={(event) =>
+ onValueChange(value.id, (current) => ({
+ ...current,
+ description: event.target.value,
+ }))
+ }
+ />
+ </td>
+ </tr>
+ )
+}
+
+function ArrayItemsEditor({
+ property,
+ onChange,
+ depth,
+ dropPreview,
+ nestedEditorOpenByPropertyId,
+ onNestedEditorOpenChange,
+}: {
+ property: SchemaBuilderProperty
+ onChange: (property: SchemaBuilderProperty) => void
+ depth: number
+ dropPreview: PropertyMovePreview | null
+ nestedEditorOpenByPropertyId: Record<string, boolean>
+ onNestedEditorOpenChange: (propertyId: string, open: boolean) => void
+}) {
+ const items = property.items ?? { type: "string" as const }
+
+ return (
+ <>
+ {items.type === "object" ? (
+ <SchemaBuilderTable
+ properties={items.properties ?? []}
+ depth={depth + 1}
+ containerId={getArrayObjectContainerId(property.id)}
+ dropPreview={dropPreview}
+ nestedEditorOpenByPropertyId={nestedEditorOpenByPropertyId}
+ onNestedEditorOpenChange={onNestedEditorOpenChange}
+ onPropertiesChange={(properties) =>
+ onChange({
+ ...property,
+ items: {
+ type: "object",
+ properties,
+ },
+ })
+ }
+ />
+ ) : items.type === "enum" ? (
+ <EnumEditor
+ values={items.enumValues ?? []}
+ onChange={(enumValues) =>
+ onChange({
+ ...property,
+ items: {
+ type: "enum",
+ enumValues,
+ },
+ })
+ }
+ />
+ ) : null}
+ </>
+ )
+}
+
+function NestedEditor({
+ property,
+ depth,
+ onChange,
+ dropPreview,
+ nestedEditorOpenByPropertyId,
+ onNestedEditorOpenChange,
+}: {
+ property: SchemaBuilderProperty
+ depth: number
+ onChange: (property: SchemaBuilderProperty) => void
+ dropPreview: PropertyMovePreview | null
+ nestedEditorOpenByPropertyId: Record<string, boolean>
+ onNestedEditorOpenChange: (propertyId: string, open: boolean) => void
+}) {
+ if (property.type === "enum") {
+ return (
+ <EnumEditor
+ values={property.enumValues ?? []}
+ onChange={(enumValues) => onChange({ ...property, enumValues })}
+ />
+ )
+ }
+
+ if (property.type === "object") {
+ return (
+ <SchemaBuilderTable
+ properties={property.properties ?? []}
+ depth={depth + 1}
+ containerId={getObjectContainerId(property.id)}
+ dropPreview={dropPreview}
+ nestedEditorOpenByPropertyId={nestedEditorOpenByPropertyId}
+ onNestedEditorOpenChange={onNestedEditorOpenChange}
+ onPropertiesChange={(properties) =>
+ onChange({ ...property, properties })
+ }
+ />
+ )
+ }
+
+ if (property.type === "array") {
+ return (
+ <ArrayItemsEditor
+ property={property}
+ depth={depth}
+ dropPreview={dropPreview}
+ nestedEditorOpenByPropertyId={nestedEditorOpenByPropertyId}
+ onNestedEditorOpenChange={onNestedEditorOpenChange}
+ onChange={onChange}
+ />
+ )
+ }
+
+ return null
+}
+
+function SchemaBuilderTable({
+ properties,
+ depth = 0,
+ containerId = ROOT_SCHEMA_CONTAINER_ID,
+ dropPreview,
+ nestedEditorOpenByPropertyId,
+ onNestedEditorOpenChange,
+ onPropertiesChange,
+}: {
+ properties: SchemaBuilderProperty[]
+ depth?: number
+ containerId?: string
+ dropPreview: PropertyMovePreview | null
+ nestedEditorOpenByPropertyId: Record<string, boolean>
+ onNestedEditorOpenChange: (propertyId: string, open: boolean) => void
+ onPropertiesChange: (properties: SchemaBuilderProperty[]) => void
+}) {
+ const { setNodeRef } = useDroppable({
+ id: containerId,
+ data: {
+ type: SCHEMA_PROPERTY_DRAG_TYPE,
+ containerId,
+ },
+ })
+ const sortableItems = React.useMemo(
+ () => properties.map((property) => property.id),
+ [properties]
+ )
+ const updateProperty = React.useCallback(
+ (
+ id: string,
+ update: (property: SchemaBuilderProperty) => SchemaBuilderProperty
+ ) => {
+ onPropertiesChange(updatePropertyById(properties, id, update))
+ },
+ [onPropertiesChange, properties]
+ )
+
+ const addProperty = React.useCallback(() => {
+ onPropertiesChange([...properties, createProperty()])
+ }, [onPropertiesChange, properties])
+ const tableDropPreview =
+ dropPreview?.containerId === containerId ? dropPreview : null
+
+ return (
+ <div
+ ref={setNodeRef}
+ className="overflow-visible rounded-lg border bg-background"
+ >
+ <table className="w-full table-fixed border-collapse text-sm">
+ <thead>
+ <tr className="border-b bg-muted/55 text-xs text-muted-foreground">
+ <th className="w-[28%] px-3 py-2 text-left font-medium">
+ Property key
+ </th>
+ <th className="w-[22%] border-l px-3 py-2 text-left font-medium">
+ Type
+ </th>
+ <th className="border-l px-3 py-2 text-left font-medium">
+ Description
+ </th>
+ </tr>
+ </thead>
+ <SortableContext
+ id={containerId}
+ items={sortableItems}
+ strategy={verticalListSortingStrategy}
+ >
+ {properties.map((property, index) => (
+ <React.Fragment key={property.id}>
+ {tableDropPreview?.index === index ? (
+ <SchemaPropertyDropPreviewRows
+ property={tableDropPreview.property}
+ />
+ ) : null}
+ <SortablePropertyRows
+ property={property}
+ depth={depth}
+ dropPreview={dropPreview}
+ nestedEditorOpenByPropertyId={nestedEditorOpenByPropertyId}
+ onNestedEditorOpenChange={onNestedEditorOpenChange}
+ onPropertyChange={(nextProperty) =>
+ updateProperty(property.id, () => nextProperty)
+ }
+ />
+ </React.Fragment>
+ ))}
+ {tableDropPreview?.index === properties.length ? (
+ <SchemaPropertyDropPreviewRows
+ property={tableDropPreview.property}
+ />
+ ) : null}
+ </SortableContext>
+ <tbody>
+ <tr>
+ <td colSpan={3} className="p-0">
+ <button
+ type="button"
+ className="flex h-9 w-full items-center justify-center gap-2 text-sm text-muted-foreground transition-colors outline-none hover:bg-muted/55 hover:text-foreground focus-visible:bg-muted/55 focus-visible:text-foreground"
+ onClick={addProperty}
+ >
+ <HugeiconsIcon icon={Add01Icon} className="size-4" />
+ Add property
+ </button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ )
+}
+
+function SortablePropertyRows({
+ property,
+ depth,
+ dropPreview,
+ nestedEditorOpenByPropertyId,
+ onNestedEditorOpenChange,
+ onPropertyChange,
+}: {
+ property: SchemaBuilderProperty
+ depth: number
+ dropPreview: PropertyMovePreview | null
+ nestedEditorOpenByPropertyId: Record<string, boolean>
+ onNestedEditorOpenChange: (propertyId: string, open: boolean) => void
+ onPropertyChange: (property: SchemaBuilderProperty) => void
+}) {
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({
+ id: property.id,
+ data: {
+ type: SCHEMA_PROPERTY_DRAG_TYPE,
+ },
+ })
+ const hasNestedEditor = propertyHasNestedEditor(property)
+ const isNestedEditorOpen = nestedEditorOpenByPropertyId[property.id] ?? true
+ const nestedEditorLabel = getNestedEditorLabel(property)
+
+ return (
+ <tbody
+ ref={setNodeRef}
+ className={cn(isDragging && "relative z-10 opacity-70")}
+ style={{
+ transform: CSS.Translate.toString(transform),
+ transition,
+ }}
+ >
+ <tr
+ className={cn(
+ "group/property-row border-b",
+ hasNestedEditor && "bg-muted/20"
+ )}
+ >
+ <td className="relative p-0 align-top">
+ <button
+ type="button"
+ className={cn(
+ "absolute top-1/2 left-0 z-50 grid size-5 -translate-x-1/2 -translate-y-1/2 cursor-grab place-items-center rounded-md border bg-background text-muted-foreground opacity-0 shadow-sm transition-[opacity,color,box-shadow] outline-none group-hover/property-row:opacity-100 hover:text-foreground focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing",
+ isDragging && "opacity-100"
+ )}
+ aria-label={`Drag ${property.key || "property"}`}
+ {...attributes}
+ {...listeners}
+ >
+ <HugeiconsIcon icon={DragDropVerticalIcon} className="size-3.5" />
+ </button>
+ <div className="min-w-0">
+ <InlineTextInput
+ value={property.key}
+ placeholder={depth ? "nested_key" : "property_key"}
+ className="font-mono"
+ spellCheck={false}
+ onChange={(event) =>
+ onPropertyChange({
+ ...property,
+ key: event.target.value,
+ })
+ }
+ />
+ </div>
+ </td>
+ <td className="border-l p-1 align-top">
+ <SchemaTypeMenu property={property} onChange={onPropertyChange} />
+ </td>
+ <td className="border-l p-0 align-top">
+ <InlineTextInput
+ value={property.description}
+ placeholder="Describe what this field should extract."
+ onChange={(event) =>
+ onPropertyChange({
+ ...property,
+ description: event.target.value,
+ })
+ }
+ />
+ </td>
+ </tr>
+ {hasNestedEditor ? (
+ <tr className="border-b bg-muted/20">
+ <td colSpan={3} className="p-0">
+ <Collapsible
+ open={isNestedEditorOpen}
+ onOpenChange={(open) =>
+ onNestedEditorOpenChange(property.id, open)
+ }
+ >
+ <div className="group/collapsible-trigger-row flex h-8 w-full items-center transition-colors focus-within:bg-muted/55 hover:bg-muted/55">
+ <CollapsibleTrigger
+ className="flex h-full min-w-0 flex-1 items-center gap-2 px-3 text-left text-xs font-medium text-muted-foreground transition-colors outline-none group-hover/collapsible-trigger-row:text-foreground focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
+ type="button"
+ >
+ <HugeiconsIcon
+ icon={ChevronDown}
+ className={cn(
+ "size-3.5 shrink-0 transition-transform duration-200",
+ !isNestedEditorOpen && "-rotate-90"
+ )}
+ />
+ <span className="min-w-0 truncate">{nestedEditorLabel}</span>
+ </CollapsibleTrigger>
+ {property.type === "array" ? (
+ <div className="flex h-full shrink-0 items-center px-2">
+ <ArrayItemTypeMenu
+ property={property}
+ onChange={onPropertyChange}
+ />
+ </div>
+ ) : null}
+ </div>
+ <CollapsiblePanel>
+ <div
+ className="p-2 pl-[--schema-builder-nest-indent]"
+ style={
+ {
+ "--schema-builder-nest-indent": `${
+ 0.5 + Math.min(depth, 4) * 0.75
+ }rem`,
+ } as React.CSSProperties
+ }
+ >
+ <NestedEditor
+ property={property}
+ depth={depth}
+ dropPreview={dropPreview}
+ nestedEditorOpenByPropertyId={nestedEditorOpenByPropertyId}
+ onNestedEditorOpenChange={onNestedEditorOpenChange}
+ onChange={onPropertyChange}
+ />
+ </div>
+ </CollapsiblePanel>
+ </Collapsible>
+ </td>
+ </tr>
+ ) : null}
+ </tbody>
+ )
+}
+
+function SchemaPropertyDropPreviewRows({
+ property,
+}: {
+ property: SchemaBuilderProperty
+}) {
+ return (
+ <tbody
+ className="pointer-events-none"
+ aria-label={`Insert ${property.key || "property"} here`}
+ >
+ <tr className="h-0">
+ <td colSpan={3} className="p-0">
+ <div className="relative z-20 h-0 overflow-visible">
+ <div className="absolute inset-x-2 top-0 h-px -translate-y-1/2 bg-primary" />
+ <div className="absolute top-0 left-2 size-1.5 -translate-y-1/2 rounded-full bg-primary" />
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ )
+}
+
+function SchemaPropertyDragOverlay({
+ property,
+ isNestedEditorOpen,
+ nestedEditorOpenByPropertyId,
+}: {
+ property: SchemaBuilderProperty
+ isNestedEditorOpen: boolean
+ nestedEditorOpenByPropertyId: Record<string, boolean>
+}) {
+ const hasNestedEditor = propertyHasNestedEditor(property)
+
+ return (
+ <div className="w-[min(680px,calc(100vw-2rem))] overflow-hidden rounded-lg border bg-background text-sm shadow-lg">
+ <div
+ className={cn(
+ "grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1.35fr)] items-center",
+ hasNestedEditor && "bg-muted/20"
+ )}
+ >
+ <div className="min-w-0 px-3 py-2 font-mono">
+ <span className="block truncate">
+ {property.key || "property_key"}
+ </span>
+ </div>
+ <div className="border-l px-2 py-1.5">
+ <SchemaTypeBadge type={getTypeStyleKey(property)} />
+ </div>
+ <div className="min-w-0 border-l px-3 py-2 text-muted-foreground">
+ <span className="block truncate">
+ {property.description || "Describe what this field should extract."}
+ </span>
+ </div>
+ </div>
+ {hasNestedEditor ? (
+ <div className="border-t bg-muted/20">
+ <div className="flex h-8 items-center gap-2 px-3 text-xs font-medium text-muted-foreground">
+ <HugeiconsIcon
+ icon={ChevronDown}
+ className={cn(
+ "size-3.5 shrink-0",
+ !isNestedEditorOpen && "-rotate-90"
+ )}
+ />
+ <span className="min-w-0 truncate">
+ {getNestedEditorLabel(property)}
+ </span>
+ {property.type === "array" ? (
+ <div className="ml-auto shrink-0">
+ <SchemaTypeBadge
+ type={`array-${property.items?.type ?? "string"}`}
+ />
+ </div>
+ ) : null}
+ </div>
+ {isNestedEditorOpen ? (
+ <div className="max-h-[280px] overflow-hidden p-2">
+ <NestedEditorPreview
+ property={property}
+ nestedEditorOpenByPropertyId={nestedEditorOpenByPropertyId}
+ />
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ )
+}
+
+function NestedEditorPreview({
+ property,
+ nestedEditorOpenByPropertyId,
+}: {
+ property: SchemaBuilderProperty
+ nestedEditorOpenByPropertyId: Record<string, boolean>
+}) {
+ if (property.type === "enum") {
+ return <EnumValuesPreview values={property.enumValues ?? []} />
+ }
+
+ if (property.type === "object") {
+ return (
+ <SchemaPropertiesPreview
+ properties={property.properties ?? []}
+ nestedEditorOpenByPropertyId={nestedEditorOpenByPropertyId}
+ />
+ )
+ }
+
+ if (property.type === "array") {
+ const items = property.items ?? { type: "string" as const }
+
+ if (items.type === "enum") {
+ return <EnumValuesPreview values={items.enumValues ?? []} />
+ }
+
+ if (items.type === "object") {
+ return (
+ <SchemaPropertiesPreview
+ properties={items.properties ?? []}
+ nestedEditorOpenByPropertyId={nestedEditorOpenByPropertyId}
+ />
+ )
+ }
+ }
+
+ return null
+}
+
+function EnumValuesPreview({ values }: { values: SchemaBuilderEnumValue[] }) {
+ return (
+ <div className="overflow-hidden rounded-lg border bg-background">
+ <div className="grid grid-cols-[minmax(0,0.85fr)_minmax(0,1.15fr)] border-b bg-muted/55 text-xs font-medium text-muted-foreground">
+ <div className="px-3 py-2">Value</div>
+ <div className="border-l px-3 py-2">Description</div>
+ </div>
+ {values.map((value) => (
+ <div
+ key={value.id}
+ className="grid grid-cols-[minmax(0,0.85fr)_minmax(0,1.15fr)] border-b last:border-b-0"
+ >
+ <div className="min-w-0 px-3 py-2 font-mono">
+ <span className="block truncate">{value.value || "value"}</span>
+ </div>
+ <div className="min-w-0 border-l px-3 py-2 text-muted-foreground">
+ <span className="block truncate">
+ {value.description || "Description"}
+ </span>
+ </div>
+ </div>
+ ))}
+ </div>
+ )
+}
+
+function SchemaPropertiesPreview({
+ properties,
+ nestedEditorOpenByPropertyId,
+}: {
+ properties: SchemaBuilderProperty[]
+ nestedEditorOpenByPropertyId: Record<string, boolean>
+}) {
+ return (
+ <div className="overflow-hidden rounded-lg border bg-background">
+ <div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1.25fr)] border-b bg-muted/55 text-xs font-medium text-muted-foreground">
+ <div className="px-3 py-2">Property key</div>
+ <div className="border-l px-3 py-2">Type</div>
+ <div className="border-l px-3 py-2">Description</div>
+ </div>
+ {properties.map((property) => {
+ const hasNestedEditor = propertyHasNestedEditor(property)
+ const isNestedEditorOpen =
+ nestedEditorOpenByPropertyId[property.id] ?? true
+
+ return (
+ <div key={property.id} className="border-b last:border-b-0">
+ <div
+ className={cn(
+ "grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1.25fr)] items-center",
+ hasNestedEditor && "bg-muted/20"
+ )}
+ >
+ <div className="min-w-0 px-3 py-2 font-mono">
+ <span className="block truncate">
+ {property.key || "property_key"}
+ </span>
+ </div>
+ <div className="border-l px-2 py-1.5">
+ <SchemaTypeBadge type={getTypeStyleKey(property)} />
+ </div>
+ <div className="min-w-0 border-l px-3 py-2 text-muted-foreground">
+ <span className="block truncate">
+ {property.description || "Description"}
+ </span>
+ </div>
+ </div>
+ {hasNestedEditor ? (
+ <div className="border-t bg-muted/20">
+ <div className="flex h-7 items-center gap-2 px-3 text-xs font-medium text-muted-foreground">
+ <HugeiconsIcon
+ icon={ChevronDown}
+ className={cn(
+ "size-3.5 shrink-0",
+ !isNestedEditorOpen && "-rotate-90"
+ )}
+ />
+ <span className="min-w-0 truncate">
+ {getNestedEditorLabel(property)}
+ </span>
+ </div>
+ {isNestedEditorOpen ? (
+ <div className="p-2">
+ <NestedEditorPreview
+ property={property}
+ nestedEditorOpenByPropertyId={
+ nestedEditorOpenByPropertyId
+ }
+ />
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ )
+ })}
+ </div>
+ )
+}
+
+export function SchemaJsonView({
+ scrollResetKey = 0,
+ schema,
+ theme,
+}: {
+ scrollResetKey?: React.Key
+ schema: SchemaBuilderSchema
+ theme?: SchemaBuilderTheme
+}) {
+ const codeThemeType = useResolvedCodeThemeType(theme)
+ const file = React.useMemo(() => {
+ const contents = formatJson(serializeSchema(schema))
+
+ return {
+ name: "schema.json",
+ contents,
+ lang: "json" as const,
+ cacheKey: contents,
+ }
+ }, [schema])
+
+ return (
+ <div
+ data-rehype-pretty-code-figure
+ className="relative m-0! h-full overflow-hidden rounded-none! bg-code text-code-foreground"
+ >
+ <WorkerPoolContextProvider
+ poolOptions={CODE_WORKER_POOL_OPTIONS}
+ highlighterOptions={CODE_HIGHLIGHTER_OPTIONS}
+ >
+ <Virtualizer
+ key={`${file.cacheKey}:${codeThemeType}:${String(scrollResetKey)}`}
+ className="no-scrollbar h-full min-w-0 overflow-auto overscroll-contain outline-none"
+ contentClassName="min-w-full"
+ >
+ <File
+ key={`${file.cacheKey}:${codeThemeType}`}
+ className="block min-w-full"
+ file={file}
+ metrics={CODE_VIRTUAL_FILE_METRICS}
+ style={CODE_FILE_THEME}
+ options={{
+ disableFileHeader: true,
+ overflow: "scroll",
+ themeType: codeThemeType,
+ theme: {
+ light: "pierre-light-soft",
+ dark: "pierre-dark-soft",
+ },
+ }}
+ />
+ </Virtualizer>
+ </WorkerPoolContextProvider>
+ </div>
+ )
+}
+
+export function SchemaBuilderPanel({
+ className,
+ defaultSchema = SAMPLE_SCHEMA,
+ schema: controlledSchema,
+ onSchemaChange,
+ theme,
+}: {
+ className?: string
+ defaultSchema?: SchemaBuilderSchema
+ schema?: SchemaBuilderSchema
+ onSchemaChange?: (schema: SchemaBuilderSchema) => void
+ theme?: SchemaBuilderTheme
+} = {}) {
+ const [activeTab, setActiveTab] = React.useState("form")
+ const [jsonScrollResetKey, setJsonScrollResetKey] = React.useState(0)
+ const sensors = useSchemaBuilderSensors()
+ const dndContextId = React.useId()
+ const lastSchemaOverIdRef = React.useRef<UniqueIdentifier | null>(null)
+ const [activeDragProperty, setActiveDragProperty] =
+ React.useState<SchemaBuilderProperty | null>(null)
+ const [activeSchemaDrag, setActiveSchemaDrag] = React.useState<{
+ activeId: string
+ overId: string | null
+ } | null>(null)
+ const [nestedEditorOpenByPropertyId, setNestedEditorOpenByPropertyId] =
+ React.useState<Record<string, boolean>>({})
+ const [uncontrolledSchema, setUncontrolledSchema] =
+ React.useState(defaultSchema)
+ const schema = controlledSchema ?? uncontrolledSchema
+ const dropPreview = React.useMemo(() => {
+ if (!activeSchemaDrag?.overId) return null
+
+ return getPropertyMovePreview(
+ schema.properties,
+ activeSchemaDrag.activeId,
+ activeSchemaDrag.overId
+ )
+ }, [activeSchemaDrag, schema.properties])
+
+ const updateSchema = React.useCallback(
+ (nextSchema: SchemaBuilderSchema) => {
+ if (!controlledSchema) {
+ setUncontrolledSchema(nextSchema)
+ }
+
+ onSchemaChange?.(nextSchema)
+ },
+ [controlledSchema, onSchemaChange]
+ )
+ const handleNestedEditorOpenChange = React.useCallback(
+ (propertyId: string, open: boolean) => {
+ setNestedEditorOpenByPropertyId((current) => {
+ if ((current[propertyId] ?? true) === open) return current
+
+ return {
+ ...current,
+ [propertyId]: open,
+ }
+ })
+ },
+ []
+ )
+ const schemaCollisionDetection = React.useCallback<CollisionDetection>(
+ (args) => {
+ if (args.active.data.current?.type !== SCHEMA_PROPERTY_DRAG_TYPE) {
+ return closestCenter(args)
+ }
+
+ const pointerIntersections = pointerWithin(args)
+ const schemaPointerIntersections = pointerIntersections
+ .filter(({ id }) =>
+ isSchemaCollisionCandidate(
+ schema.properties,
+ id,
+ args.active.id,
+ args
+ )
+ )
+ .sort(
+ (first, second) =>
+ getDroppableRectArea(args.droppableRects, first.id) -
+ getDroppableRectArea(args.droppableRects, second.id)
+ )
+ const isPointerOverActive = pointerIntersections.some(
+ ({ id }) => id === args.active.id
+ )
+
+ if (
+ schemaPointerIntersections.length === 0 &&
+ isPointerOverActive &&
+ lastSchemaOverIdRef.current
+ ) {
+ return [{ id: lastSchemaOverIdRef.current }]
+ }
+
+ const intersections =
+ schemaPointerIntersections.length > 0
+ ? schemaPointerIntersections
+ : rectIntersection(args).filter(({ id }) =>
+ isSchemaCollisionCandidate(
+ schema.properties,
+ id,
+ args.active.id,
+ args
+ )
+ )
+ let overId = getFirstCollision(intersections, "id")
+
+ if (overId != null) {
+ overId =
+ getProjectedPropertyChildContainerId(
+ schema.properties,
+ overId,
+ args
+ ) ?? overId
+
+ if (isPropertyContainerId(overId)) {
+ const containerProperties = getContainerProperties(
+ schema.properties,
+ String(overId)
+ )
+
+ if (
+ containerProperties.length > 0 &&
+ !isPointerBelowLastContainerProperty(containerProperties, args)
+ ) {
+ const closestChild = closestCenter({
+ ...args,
+ droppableContainers: args.droppableContainers.filter(
+ (container) =>
+ container.id !== overId &&
+ containerProperties.some(
+ (property) => property.id === container.id
+ ) &&
+ isSchemaCollisionCandidate(
+ schema.properties,
+ container.id,
+ args.active.id,
+ args
+ )
+ ),
+ })
+ const closestChildId = getFirstCollision(closestChild, "id")
+
+ overId = closestChildId
+ ? (getProjectedPropertyChildContainerId(
+ schema.properties,
+ closestChildId,
+ args
+ ) ?? closestChildId)
+ : overId
+ }
+ }
+
+ lastSchemaOverIdRef.current = overId
+
+ return [{ id: overId }]
+ }
+
+ return lastSchemaOverIdRef.current
+ ? [{ id: lastSchemaOverIdRef.current }]
+ : []
+ },
+ [schema.properties]
+ )
+ const handleSchemaDragStart = React.useCallback(
+ (event: DragStartEvent) => {
+ if (event.active.data.current?.type !== SCHEMA_PROPERTY_DRAG_TYPE) {
+ return
+ }
+
+ lastSchemaOverIdRef.current = null
+ const activeId = String(event.active.id)
+ setActiveDragProperty(
+ findPropertyLocation(schema.properties, activeId)?.property ?? null
+ )
+ setActiveSchemaDrag({
+ activeId,
+ overId: null,
+ })
+ },
+ [schema.properties]
+ )
+ const handleSchemaDragOver = React.useCallback(
+ (event: DragOverEvent) => {
+ if (event.active.data.current?.type !== SCHEMA_PROPERTY_DRAG_TYPE) {
+ return
+ }
+
+ const activeId = String(event.active.id)
+ const eventOverId = event.over ? String(event.over.id) : null
+ const candidateOverIds = [
+ eventOverId,
+ lastSchemaOverIdRef.current
+ ? String(lastSchemaOverIdRef.current)
+ : null,
+ ]
+ const overId =
+ candidateOverIds.find(
+ (candidateOverId) =>
+ candidateOverId &&
+ candidateOverId !== activeId &&
+ getPropertyMovePreview(schema.properties, activeId, candidateOverId)
+ ) ?? null
+
+ setActiveSchemaDrag((current) => {
+ if (current?.activeId === activeId && current?.overId === overId) {
+ return current
+ }
+
+ return {
+ activeId,
+ overId,
+ }
+ })
+ },
+ [schema.properties]
+ )
+ const handleSchemaDragEnd = React.useCallback(
+ (event: DragEndEvent) => {
+ setActiveDragProperty(null)
+ setActiveSchemaDrag(null)
+
+ const { active, over } = event
+ if (active.data.current?.type !== SCHEMA_PROPERTY_DRAG_TYPE) {
+ lastSchemaOverIdRef.current = null
+ return
+ }
+
+ const activeId = String(active.id)
+ const candidateOverIds = [
+ over ? String(over.id) : null,
+ lastSchemaOverIdRef.current
+ ? String(lastSchemaOverIdRef.current)
+ : null,
+ ]
+ const overId =
+ candidateOverIds.find(
+ (candidateOverId) => candidateOverId && candidateOverId !== activeId
+ ) ?? null
+
+ lastSchemaOverIdRef.current = null
+
+ if (!overId) return
+
+ const nextProperties = moveProperty(schema.properties, activeId, overId)
+
+ if (nextProperties === schema.properties) return
+
+ updateSchema({
+ properties: nextProperties,
+ })
+ },
+ [schema.properties, updateSchema]
+ )
+ const handleSchemaDragCancel = React.useCallback(() => {
+ lastSchemaOverIdRef.current = null
+ setActiveDragProperty(null)
+ setActiveSchemaDrag(null)
+ }, [])
+ const handleTabChange = React.useCallback((nextTab: string) => {
+ setActiveTab(nextTab)
+
+ if (nextTab === "json") {
+ setJsonScrollResetKey((current) => current + 1)
+ }
+ }, [])
+
+ return (
+ <Tabs
+ value={activeTab}
+ onValueChange={handleTabChange}
+ className={cn("flex h-[560px] flex-col gap-0 bg-background", className)}
+ >
+ <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">
+ <TabsList className="h-8 sm:h-7">
+ <TabsTrigger value="form" className="h-7 sm:h-6">
+ <HugeiconsIcon icon={TableIcon} className="size-4" />
+ Form
+ </TabsTrigger>
+ <TabsTrigger value="json" className="h-7 sm:h-6">
+ <HugeiconsIcon icon={SourceCodeSquareIcon} className="size-4" />
+ JSON
+ </TabsTrigger>
+ </TabsList>
+ </div>
+ <TabsContent value="form" keepMounted className="min-h-0 flex-1">
+ <ScrollArea className="h-full" scrollFade>
+ <DndContext
+ id={`schema-builder-${dndContextId}`}
+ autoScroll={false}
+ sensors={sensors}
+ collisionDetection={schemaCollisionDetection}
+ measuring={SCHEMA_DND_MEASURING}
+ onDragStart={handleSchemaDragStart}
+ onDragOver={handleSchemaDragOver}
+ onDragEnd={handleSchemaDragEnd}
+ onDragCancel={handleSchemaDragCancel}
+ >
+ <div className="p-3">
+ <SchemaBuilderTable
+ properties={schema.properties}
+ dropPreview={dropPreview}
+ nestedEditorOpenByPropertyId={nestedEditorOpenByPropertyId}
+ onNestedEditorOpenChange={handleNestedEditorOpenChange}
+ onPropertiesChange={(properties) =>
+ updateSchema({ properties })
+ }
+ />
+ </div>
+ <DragOverlay adjustScale={false}>
+ {activeDragProperty ? (
+ <SchemaPropertyDragOverlay
+ property={activeDragProperty}
+ isNestedEditorOpen={
+ nestedEditorOpenByPropertyId[activeDragProperty.id] ?? true
+ }
+ nestedEditorOpenByPropertyId={nestedEditorOpenByPropertyId}
+ />
+ ) : null}
+ </DragOverlay>
+ </DndContext>
+ </ScrollArea>
+ </TabsContent>
+ <TabsContent value="json" keepMounted className="min-h-0 flex-1">
+ <SchemaJsonView
+ scrollResetKey={jsonScrollResetKey}
+ schema={schema}
+ theme={theme}
+ />
+ </TabsContent>
+ </Tabs>
+ )
+}