made-refine 0.2.13 → 0.2.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +388 -49
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +388 -49
- package/dist/index.mjs.map +1 -1
- package/dist/{utils-DvJ3xKrO.d.mts → utils-lksVP2Wq.d.mts} +14 -1
- package/dist/{utils-DvJ3xKrO.d.ts → utils-lksVP2Wq.d.ts} +14 -1
- package/dist/utils.d.mts +1 -1
- package/dist/utils.d.ts +1 -1
- package/dist/utils.js +224 -19
- package/dist/utils.js.map +1 -1
- package/dist/utils.mjs +222 -19
- package/dist/utils.mjs.map +1 -1
- package/package.json +1 -1
package/dist/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils.ts","../src/utils/css-value.ts","../src/canvas-store.ts","../src/utils/measurements.ts"],"sourcesContent":["import type {\n CSSPropertyValue,\n SpacingProperties,\n BorderRadiusProperties,\n BorderStyle,\n BorderProperties,\n FlexProperties,\n SizingProperties,\n SizingValue,\n SizingMode,\n SpacingPropertyKey,\n BorderRadiusPropertyKey,\n BorderPropertyKey,\n FlexPropertyKey,\n SizingPropertyKey,\n TypographyPropertyKey,\n TypographyProperties,\n ElementInfo,\n ReactComponentFrame,\n ElementLocator,\n DomSourceLocation,\n ColorValue,\n ColorProperties,\n ColorPropertyKey,\n MeasurementLine,\n Guideline,\n DropIndicator,\n SessionEdit,\n SessionItem,\n AnchorRef,\n PlacementRef,\n MoveClassification,\n MoveOperation,\n MoveIntent,\n MovePlan,\n LayoutPrescription,\n Comment,\n} from './types'\n\nexport { parsePropertyValue, formatPropertyValue } from './utils/css-value'\nimport { parsePropertyValue } from './utils/css-value'\nimport { getCanvasSnapshot, getBodyOffset } from './canvas-store'\nimport { getZoomScale } from './utils/measurements'\n\nexport function clamp(value: number, min: number, max: number): number {\n if (!Number.isFinite(value)) return min\n if (max < min) return min\n return Math.max(min, Math.min(max, value))\n}\n\nexport function isInputFocused(): boolean {\n let active: Element | null = document.activeElement\n while (active?.shadowRoot?.activeElement) {\n active = active.shadowRoot.activeElement\n }\n return (\n active instanceof HTMLInputElement ||\n active instanceof HTMLTextAreaElement ||\n (active instanceof HTMLElement && active.isContentEditable)\n )\n}\n\ndeclare global {\n interface Window {\n __DIRECT_EDIT_DEVTOOLS__?: {\n getFiberForElement: (element: HTMLElement) => unknown | null\n hasHook?: boolean\n }\n }\n}\n\nexport function getComputedStyles(element: HTMLElement): {\n spacing: SpacingProperties\n borderRadius: BorderRadiusProperties\n flex: FlexProperties\n} {\n const computed = window.getComputedStyle(element)\n\n return {\n spacing: {\n paddingTop: parsePropertyValue(computed.paddingTop),\n paddingRight: parsePropertyValue(computed.paddingRight),\n paddingBottom: parsePropertyValue(computed.paddingBottom),\n paddingLeft: parsePropertyValue(computed.paddingLeft),\n marginTop: parsePropertyValue(computed.marginTop),\n marginRight: parsePropertyValue(computed.marginRight),\n marginBottom: parsePropertyValue(computed.marginBottom),\n marginLeft: parsePropertyValue(computed.marginLeft),\n gap: parsePropertyValue(computed.gap || '0px'),\n },\n borderRadius: {\n borderTopLeftRadius: parsePropertyValue(computed.borderTopLeftRadius),\n borderTopRightRadius: parsePropertyValue(computed.borderTopRightRadius),\n borderBottomRightRadius: parsePropertyValue(computed.borderBottomRightRadius),\n borderBottomLeftRadius: parsePropertyValue(computed.borderBottomLeftRadius),\n },\n flex: {\n display: computed.display,\n flexDirection: computed.flexDirection as FlexProperties['flexDirection'],\n justifyContent: computed.justifyContent,\n alignItems: computed.alignItems,\n },\n }\n}\n\nexport function getComputedBorderStyles(element: HTMLElement): BorderProperties {\n const computed = window.getComputedStyle(element)\n\n const topStyle = computed.borderTopStyle as BorderStyle\n const rightStyle = computed.borderRightStyle as BorderStyle\n const bottomStyle = computed.borderBottomStyle as BorderStyle\n const leftStyle = computed.borderLeftStyle as BorderStyle\n\n const topWidth = parsePropertyValue(computed.borderTopWidth)\n const rightWidth = parsePropertyValue(computed.borderRightWidth)\n const bottomWidth = parsePropertyValue(computed.borderBottomWidth)\n const leftWidth = parsePropertyValue(computed.borderLeftWidth)\n\n return {\n borderTopStyle: topStyle,\n borderTopWidth: topWidth,\n borderRightStyle: rightStyle,\n borderRightWidth: rightWidth,\n borderBottomStyle: bottomStyle,\n borderBottomWidth: bottomWidth,\n borderLeftStyle: leftStyle,\n borderLeftWidth: leftWidth,\n }\n}\n\n/** CSS properties captured before editing so resetToOriginal can restore them. */\nexport const ORIGINAL_STYLE_PROPS = [\n 'padding-top',\n 'padding-right',\n 'padding-bottom',\n 'padding-left',\n 'padding',\n 'margin-top',\n 'margin-right',\n 'margin-bottom',\n 'margin-left',\n 'margin',\n 'gap',\n 'border-radius',\n 'border-top-left-radius',\n 'border-top-right-radius',\n 'border-bottom-right-radius',\n 'border-bottom-left-radius',\n 'border',\n 'border-style',\n 'border-width',\n 'border-top-style',\n 'border-top-width',\n 'border-right-style',\n 'border-right-width',\n 'border-bottom-style',\n 'border-bottom-width',\n 'border-left-style',\n 'border-left-width',\n 'display',\n 'flex-direction',\n 'justify-content',\n 'align-items',\n 'width',\n 'height',\n 'background-color',\n 'background',\n 'color',\n 'border-color',\n 'outline-color',\n 'outline-style',\n 'outline-width',\n 'box-shadow',\n 'font-family',\n 'font-weight',\n 'font-size',\n 'line-height',\n 'letter-spacing',\n 'text-align',\n] as const\n\nexport function getOriginalInlineStyles(element: HTMLElement): Record<string, string> {\n const styles: Record<string, string> = {}\n\n for (const prop of ORIGINAL_STYLE_PROPS) {\n const value = element.style.getPropertyValue(prop)\n if (value) {\n styles[prop] = value\n }\n }\n\n return styles\n}\n\nconst spacingScale: Record<number, string> = { 0: '0', 1: 'px', 2: '0.5', 4: '1', 8: '2', 12: '3', 16: '4', 20: '5', 24: '6', 32: '8' }\n\nconst tailwindClassMap: Record<string, { prefix: string; scale: Record<number, string> }> = {\n padding: { prefix: 'p', scale: spacingScale },\n 'padding-inline': { prefix: 'px', scale: spacingScale },\n 'padding-block': { prefix: 'py', scale: spacingScale },\n 'padding-top': { prefix: 'pt', scale: spacingScale },\n 'padding-right': { prefix: 'pr', scale: spacingScale },\n 'padding-bottom': { prefix: 'pb', scale: spacingScale },\n 'padding-left': { prefix: 'pl', scale: spacingScale },\n margin: { prefix: 'm', scale: spacingScale },\n 'margin-inline': { prefix: 'mx', scale: spacingScale },\n 'margin-block': { prefix: 'my', scale: spacingScale },\n 'margin-top': { prefix: 'mt', scale: spacingScale },\n 'margin-right': { prefix: 'mr', scale: spacingScale },\n 'margin-bottom': { prefix: 'mb', scale: spacingScale },\n 'margin-left': { prefix: 'ml', scale: spacingScale },\n gap: { prefix: 'gap', scale: spacingScale },\n 'border-width': {\n prefix: 'border',\n scale: { 0: '0', 1: '', 2: '2', 4: '4', 8: '8' },\n },\n 'border-top-width': {\n prefix: 'border-t',\n scale: { 0: '0', 1: '', 2: '2', 4: '4', 8: '8' },\n },\n 'border-right-width': {\n prefix: 'border-r',\n scale: { 0: '0', 1: '', 2: '2', 4: '4', 8: '8' },\n },\n 'border-bottom-width': {\n prefix: 'border-b',\n scale: { 0: '0', 1: '', 2: '2', 4: '4', 8: '8' },\n },\n 'border-left-width': {\n prefix: 'border-l',\n scale: { 0: '0', 1: '', 2: '2', 4: '4', 8: '8' },\n },\n 'border-radius': {\n prefix: 'rounded',\n scale: { 0: 'none', 2: 'sm', 4: '', 6: 'md', 8: 'lg', 12: 'xl', 16: '2xl', 24: '3xl', 9999: 'full' },\n },\n 'border-top-left-radius': {\n prefix: 'rounded-tl',\n scale: { 0: 'none', 2: 'sm', 4: '', 6: 'md', 8: 'lg', 12: 'xl', 16: '2xl', 24: '3xl', 9999: 'full' },\n },\n 'border-top-right-radius': {\n prefix: 'rounded-tr',\n scale: { 0: 'none', 2: 'sm', 4: '', 6: 'md', 8: 'lg', 12: 'xl', 16: '2xl', 24: '3xl', 9999: 'full' },\n },\n 'border-bottom-right-radius': {\n prefix: 'rounded-br',\n scale: { 0: 'none', 2: 'sm', 4: '', 6: 'md', 8: 'lg', 12: 'xl', 16: '2xl', 24: '3xl', 9999: 'full' },\n },\n 'border-bottom-left-radius': {\n prefix: 'rounded-bl',\n scale: { 0: 'none', 2: 'sm', 4: '', 6: 'md', 8: 'lg', 12: 'xl', 16: '2xl', 24: '3xl', 9999: 'full' },\n },\n}\n\nconst flexDirectionMap: Record<string, string> = {\n row: 'flex-row',\n 'row-reverse': 'flex-row-reverse',\n column: 'flex-col',\n 'column-reverse': 'flex-col-reverse',\n}\n\nconst justifyContentMap: Record<string, string> = {\n 'flex-start': 'justify-start',\n 'flex-end': 'justify-end',\n center: 'justify-center',\n 'space-between': 'justify-between',\n 'space-around': 'justify-around',\n 'space-evenly': 'justify-evenly',\n start: 'justify-start',\n end: 'justify-end',\n}\n\nconst alignItemsMap: Record<string, string> = {\n 'flex-start': 'items-start',\n 'flex-end': 'items-end',\n center: 'items-center',\n baseline: 'items-baseline',\n stretch: 'items-stretch',\n start: 'items-start',\n end: 'items-end',\n}\n\nfunction getExactScaleValue(value: number, scale: Record<number, string>): string | null {\n if (Object.prototype.hasOwnProperty.call(scale, value)) {\n return scale[value]\n }\n return null\n}\n\nfunction normalizeTailwindArbitraryValue(value: string): string {\n return value.trim().replace(/\\s+/g, '_')\n}\n\nfunction normalizeShadowForComparison(value: string): string {\n return value\n .trim()\n .toLowerCase()\n .replace(/\\s*\\/\\s*/g, '/')\n .replace(/\\(\\s+/g, '(')\n .replace(/\\s+\\)/g, ')')\n .replace(/\\s*,\\s*/g, ',')\n .replace(/\\s+/g, ' ')\n}\n\nconst tailwindShadowClassValues: Array<{ className: string; css: string }> = [\n { className: 'shadow-2xs', css: '0 1px rgb(0 0 0 / 0.05)' },\n { className: 'shadow-xs', css: '0 1px 2px 0 rgb(0 0 0 / 0.05)' },\n { className: 'shadow', css: '0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)' },\n { className: 'shadow-sm', css: '0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)' },\n { className: 'shadow-md', css: '0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)' },\n { className: 'shadow-lg', css: '0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)' },\n { className: 'shadow-xl', css: '0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)' },\n { className: 'shadow-2xl', css: '0 25px 50px -12px rgb(0 0 0 / 0.25)' },\n { className: 'shadow-inner', css: 'inset 0 2px 4px 0 rgb(0 0 0 / 0.05)' },\n]\n\nexport function stylesToTailwind(styles: Record<string, string>): string {\n const classes: string[] = []\n\n for (const [prop, value] of Object.entries(styles)) {\n if (tailwindClassMap[prop]) {\n const parsed = parsePropertyValue(value)\n const mapping = tailwindClassMap[prop]\n if (value === 'auto') {\n classes.push(`${mapping.prefix}-auto`)\n continue\n }\n if (parsed.unit === 'px') {\n const exactScale = getExactScaleValue(parsed.numericValue, mapping.scale)\n if (exactScale !== null) {\n if (exactScale === '') {\n classes.push(mapping.prefix)\n } else {\n classes.push(`${mapping.prefix}-${exactScale}`)\n }\n continue\n }\n }\n classes.push(`${mapping.prefix}-[${value}]`)\n continue\n }\n\n if (prop === 'flex-direction' && flexDirectionMap[value]) {\n classes.push(flexDirectionMap[value])\n continue\n }\n\n if (prop === 'justify-content' && justifyContentMap[value]) {\n classes.push(justifyContentMap[value])\n continue\n }\n\n if (prop === 'align-items' && alignItemsMap[value]) {\n classes.push(alignItemsMap[value])\n continue\n }\n\n if (prop === 'display') {\n if (value === 'flex') classes.push('flex')\n else if (value === 'inline-flex') classes.push('inline-flex')\n else if (value === 'grid') classes.push('grid')\n else if (value === 'block') classes.push('block')\n else if (value === 'inline-block') classes.push('inline-block')\n else if (value === 'none') classes.push('hidden')\n continue\n }\n\n if (prop === 'width') {\n if (value === '100%') classes.push('w-full')\n else if (value === 'fit-content') classes.push('w-fit')\n else if (value === 'auto') classes.push('w-auto')\n else classes.push(`w-[${value}]`)\n continue\n }\n\n if (prop === 'height') {\n if (value === '100%') classes.push('h-full')\n else if (value === 'fit-content') classes.push('h-fit')\n else if (value === 'auto') classes.push('h-auto')\n else classes.push(`h-[${value}]`)\n continue\n }\n\n if (prop === 'background-color') {\n const colorValue = parseColorValue(value)\n classes.push(colorToTailwind('backgroundColor', colorValue))\n continue\n }\n\n if (prop === 'color') {\n const colorValue = parseColorValue(value)\n classes.push(colorToTailwind('color', colorValue))\n continue\n }\n\n if (prop === 'border-color') {\n const colorValue = parseColorValue(value)\n classes.push(colorToTailwind('borderColor', colorValue))\n continue\n }\n\n if (prop === 'border-style') {\n const styleMap: Record<string, string> = {\n none: 'border-none',\n solid: 'border-solid',\n dashed: 'border-dashed',\n dotted: 'border-dotted',\n double: 'border-double',\n }\n classes.push(styleMap[value] || `[border-style:${value}]`)\n continue\n }\n\n // Tailwind has no per-side border-style utilities — consolidate when all sides match\n if (prop === 'border-top-style' || prop === 'border-right-style' || prop === 'border-bottom-style' || prop === 'border-left-style') {\n const allPresent =\n 'border-top-style' in styles &&\n 'border-right-style' in styles &&\n 'border-bottom-style' in styles &&\n 'border-left-style' in styles\n if (allPresent) {\n // Only emit once (from border-top-style) when all four sides are present\n if (prop === 'border-top-style') {\n const allSame =\n styles['border-top-style'] === styles['border-right-style'] &&\n styles['border-top-style'] === styles['border-bottom-style'] &&\n styles['border-top-style'] === styles['border-left-style']\n if (allSame) {\n const styleMap: Record<string, string> = {\n none: 'border-none',\n solid: 'border-solid',\n dashed: 'border-dashed',\n dotted: 'border-dotted',\n double: 'border-double',\n }\n classes.push(styleMap[value] || `[border-style:${value}]`)\n } else {\n // Sides differ — emit each side individually\n classes.push(`[border-top-style:${styles['border-top-style']}]`)\n classes.push(`[border-right-style:${styles['border-right-style']}]`)\n classes.push(`[border-bottom-style:${styles['border-bottom-style']}]`)\n classes.push(`[border-left-style:${styles['border-left-style']}]`)\n }\n }\n } else {\n // Emit arbitrary-property syntax for individual side styles\n classes.push(`[${prop}:${value}]`)\n }\n continue\n }\n\n if (prop === 'outline-color') {\n const colorValue = parseColorValue(value)\n classes.push(colorToTailwind('outlineColor', colorValue))\n continue\n }\n\n if (prop === 'box-shadow') {\n const trimmed = value.trim()\n if (trimmed === 'none' || trimmed === '') {\n classes.push('shadow-none')\n } else {\n const normalized = normalizeShadowForComparison(trimmed)\n const preset = tailwindShadowClassValues.find(\n (entry) => normalizeShadowForComparison(entry.css) === normalized\n )\n if (preset) classes.push(preset.className)\n else classes.push(`shadow-[${normalizeTailwindArbitraryValue(value)}]`)\n }\n continue\n }\n\n if (prop === 'font-size') {\n classes.push(`text-[${value}]`)\n continue\n }\n\n if (prop === 'font-weight') {\n const weightMap: Record<string, string> = {\n '100': 'font-thin',\n '200': 'font-extralight',\n '300': 'font-light',\n '400': 'font-normal',\n '500': 'font-medium',\n '600': 'font-semibold',\n '700': 'font-bold',\n '800': 'font-extrabold',\n '900': 'font-black',\n }\n classes.push(weightMap[value] || `font-[${value}]`)\n continue\n }\n\n if (prop === 'line-height') {\n classes.push(`leading-[${value}]`)\n continue\n }\n\n if (prop === 'letter-spacing') {\n classes.push(`tracking-[${value}]`)\n continue\n }\n\n if (prop === 'text-align') {\n const alignMap: Record<string, string> = {\n left: 'text-left',\n center: 'text-center',\n right: 'text-right',\n justify: 'text-justify',\n }\n if (alignMap[value]) classes.push(alignMap[value])\n continue\n }\n\n if (prop === 'font-family') {\n classes.push(`font-[${value.replace(/\\s+/g, '_')}]`)\n continue\n }\n }\n\n return classes.join(' ')\n}\n\nexport const propertyToCSSMap: Record<SpacingPropertyKey, string> = {\n paddingTop: 'padding-top',\n paddingRight: 'padding-right',\n paddingBottom: 'padding-bottom',\n paddingLeft: 'padding-left',\n marginTop: 'margin-top',\n marginRight: 'margin-right',\n marginBottom: 'margin-bottom',\n marginLeft: 'margin-left',\n gap: 'gap',\n}\n\nexport const borderRadiusPropertyToCSSMap: Record<BorderRadiusPropertyKey, string> = {\n borderTopLeftRadius: 'border-top-left-radius',\n borderTopRightRadius: 'border-top-right-radius',\n borderBottomRightRadius: 'border-bottom-right-radius',\n borderBottomLeftRadius: 'border-bottom-left-radius',\n}\n\nexport const borderPropertyToCSSMap: Record<BorderPropertyKey, string> = {\n borderTopStyle: 'border-top-style',\n borderTopWidth: 'border-top-width',\n borderRightStyle: 'border-right-style',\n borderRightWidth: 'border-right-width',\n borderBottomStyle: 'border-bottom-style',\n borderBottomWidth: 'border-bottom-width',\n borderLeftStyle: 'border-left-style',\n borderLeftWidth: 'border-left-width',\n}\n\nexport const flexPropertyToCSSMap: Record<FlexPropertyKey, string> = {\n display: 'display',\n flexDirection: 'flex-direction',\n justifyContent: 'justify-content',\n alignItems: 'align-items',\n}\n\nexport const sizingPropertyToCSSMap: Record<SizingPropertyKey, string> = {\n width: 'width',\n height: 'height',\n}\n\nexport const typographyPropertyToCSSMap: Record<TypographyPropertyKey, string> = {\n fontFamily: 'font-family',\n fontWeight: 'font-weight',\n fontSize: 'font-size',\n lineHeight: 'line-height',\n letterSpacing: 'letter-spacing',\n textAlign: 'text-align',\n textVerticalAlign: 'align-items',\n}\n\nconst TEXT_ELEMENT_TAGS = new Set([\n 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',\n 'span', 'label', 'a', 'strong', 'em', 'small',\n 'blockquote', 'li', 'td', 'th', 'caption', 'figcaption',\n 'legend', 'dt', 'dd', 'abbr', 'cite', 'code', 'pre',\n])\n\nfunction hasDirectNonWhitespaceText(element: HTMLElement): boolean {\n return Array.from(element.childNodes).some(\n (node) => node.nodeType === Node.TEXT_NODE && Boolean(node.textContent?.trim())\n )\n}\n\nexport function isTextElement(element: HTMLElement): boolean {\n const tagName = element.tagName.toLowerCase()\n if (TEXT_ELEMENT_TAGS.has(tagName)) {\n return true\n }\n if (hasDirectNonWhitespaceText(element)) {\n return true\n }\n if (element.children.length === 0 && element.textContent?.trim()) {\n return true\n }\n return false\n}\n\nexport function getComputedTypography(element: HTMLElement): TypographyProperties {\n const computed = window.getComputedStyle(element)\n\n let textVerticalAlign: TypographyProperties['textVerticalAlign'] = 'flex-start'\n if (computed.display === 'flex' || computed.display === 'inline-flex') {\n const alignItems = computed.alignItems\n if (alignItems === 'center') textVerticalAlign = 'center'\n else if (alignItems === 'flex-end' || alignItems === 'end') textVerticalAlign = 'flex-end'\n }\n\n // Handle \"normal\" keyword for line-height (use font-size as approximation)\n const lineHeight = computed.lineHeight === 'normal'\n ? { numericValue: parseFloat(computed.fontSize) * 1.2, unit: 'px' as const, raw: `${Math.round(parseFloat(computed.fontSize) * 1.2)}px` }\n : parsePropertyValue(computed.lineHeight)\n\n // Handle letter-spacing: convert px to em for consistent editing\n const fontSize = parseFloat(computed.fontSize)\n let letterSpacing: CSSPropertyValue\n if (computed.letterSpacing === 'normal') {\n letterSpacing = { numericValue: 0, unit: 'em' as const, raw: '0em' }\n } else {\n const parsed = parsePropertyValue(computed.letterSpacing)\n if (parsed.unit === 'px' && fontSize > 0) {\n const emValue = Math.round((parsed.numericValue / fontSize) * 100) / 100\n letterSpacing = { numericValue: emValue, unit: 'em' as const, raw: `${emValue}em` }\n } else {\n letterSpacing = parsed\n }\n }\n\n return {\n fontFamily: computed.fontFamily,\n fontWeight: computed.fontWeight,\n fontSize: parsePropertyValue(computed.fontSize),\n lineHeight,\n letterSpacing,\n textAlign: computed.textAlign as TypographyProperties['textAlign'],\n textVerticalAlign,\n }\n}\n\nexport function detectSizingMode(\n element: HTMLElement,\n dimension: 'width' | 'height'\n): SizingMode {\n const computed = window.getComputedStyle(element)\n const inlineValue = element.style[dimension]\n\n if (inlineValue === '100%') return 'fill'\n if (inlineValue === 'auto' || inlineValue === 'fit-content') return 'fit'\n\n const computedValue = computed[dimension]\n\n if (computedValue === '100%') return 'fill'\n if (\n computedValue === 'auto' ||\n computedValue === 'fit-content' ||\n computedValue === 'max-content'\n ) {\n return 'fit'\n }\n\n const parent = element.parentElement\n if (parent) {\n const parentComputed = window.getComputedStyle(parent)\n if (parentComputed.display === 'flex' || parentComputed.display === 'inline-flex') {\n const flexGrow = computed.flexGrow\n if (flexGrow !== '0') {\n return 'fill'\n }\n }\n }\n\n if (dimension === 'width') {\n if (computed.display === 'block' && !inlineValue) {\n return 'fill'\n }\n if (\n computed.display === 'inline-block' ||\n computed.display === 'inline-flex' ||\n computed.display === 'inline'\n ) {\n return 'fit'\n }\n }\n\n if (dimension === 'height') {\n if (!inlineValue) {\n return 'fit'\n }\n }\n\n return 'fixed'\n}\n\nexport function getSizingValue(element: HTMLElement, dimension: 'width' | 'height'): SizingValue {\n const mode = detectSizingMode(element, dimension)\n const numericValue = Math.round(dimension === 'width' ? element.offsetWidth : element.offsetHeight)\n\n return {\n mode,\n value: {\n numericValue,\n unit: 'px',\n raw: `${numericValue}px`,\n },\n }\n}\n\nexport function getComputedSizing(element: HTMLElement): SizingProperties {\n return {\n width: getSizingValue(element, 'width'),\n height: getSizingValue(element, 'height'),\n }\n}\n\nexport function sizingValueToCSS(sizing: SizingValue): string {\n switch (sizing.mode) {\n case 'fill':\n return '100%'\n case 'fit':\n return 'fit-content'\n case 'fixed':\n return `${sizing.value.numericValue}${sizing.value.unit}`\n }\n}\n\nexport function sizingToTailwind(dimension: 'width' | 'height', sizing: SizingValue): string {\n const prefix = dimension === 'width' ? 'w' : 'h'\n\n switch (sizing.mode) {\n case 'fill':\n return `${prefix}-full`\n case 'fit':\n return `${prefix}-fit`\n case 'fixed':\n return `${prefix}-[${sizing.value.numericValue}${sizing.value.unit}]`\n }\n}\n\nfunction parseHexColor(hex: string): ColorValue {\n const raw = hex\n let h = hex.replace('#', '')\n\n // Expand shorthand (#RGB -> #RRGGBB)\n if (h.length === 3) {\n h = h\n .split('')\n .map((c) => c + c)\n .join('')\n }\n\n // Handle 8-digit hex with alpha\n if (h.length === 8) {\n const alpha = Math.round((parseInt(h.slice(6, 8), 16) / 255) * 100)\n return { hex: h.slice(0, 6).toUpperCase(), alpha, raw }\n }\n\n return { hex: h.toUpperCase(), alpha: 100, raw }\n}\n\nfunction parseRgbChannel(value: string): number | null {\n const token = value.trim()\n if (!token) return null\n\n if (token.endsWith('%')) {\n const numeric = parseFloat(token.slice(0, -1))\n if (!Number.isFinite(numeric)) return null\n return Math.round((Math.max(0, Math.min(100, numeric)) / 100) * 255)\n }\n\n const numeric = parseFloat(token)\n if (!Number.isFinite(numeric)) return null\n return Math.round(Math.max(0, Math.min(255, numeric)))\n}\n\nfunction parseRgbAlpha(value: string | undefined): number | null {\n if (value == null || value.trim() === '') return 1\n const token = value.trim()\n\n if (token.endsWith('%')) {\n const numeric = parseFloat(token.slice(0, -1))\n if (!Number.isFinite(numeric)) return null\n return Math.max(0, Math.min(100, numeric)) / 100\n }\n\n const numeric = parseFloat(token)\n if (!Number.isFinite(numeric)) return null\n return Math.max(0, Math.min(1, numeric))\n}\n\nfunction parseRgbaColor(rgba: string): ColorValue {\n const raw = rgba.trim()\n const fnMatch = raw.match(/^rgba?\\((.*)\\)$/i)\n if (!fnMatch) {\n return { hex: '000000', alpha: 100, raw: rgba }\n }\n\n const body = fnMatch[1].trim()\n let channelTokens: [string, string, string] | null = null\n let alphaToken: string | undefined\n\n const commaParts = body.split(',').map((part) => part.trim()).filter(Boolean)\n if (commaParts.length === 3 || commaParts.length === 4) {\n channelTokens = [commaParts[0], commaParts[1], commaParts[2]]\n alphaToken = commaParts[3]\n } else {\n const slashParts = body.split('/')\n if (slashParts.length === 1 || slashParts.length === 2) {\n const channels = slashParts[0].trim().split(/\\s+/).filter(Boolean)\n if (channels.length === 3) {\n channelTokens = [channels[0], channels[1], channels[2]]\n alphaToken = slashParts[1]?.trim()\n }\n }\n }\n\n if (!channelTokens) {\n return { hex: '000000', alpha: 100, raw: rgba }\n }\n\n const r = parseRgbChannel(channelTokens[0])\n const g = parseRgbChannel(channelTokens[1])\n const b = parseRgbChannel(channelTokens[2])\n const a = parseRgbAlpha(alphaToken)\n\n if (r === null || g === null || b === null || a === null) {\n return { hex: '000000', alpha: 100, raw: rgba }\n }\n\n const hex = [r, g, b]\n .map((v) => v.toString(16).padStart(2, '0'))\n .join('')\n .toUpperCase()\n const alpha = Math.round(a * 100)\n\n return { hex, alpha, raw: rgba }\n}\n\nfunction parseNamedColor(name: string): ColorValue {\n // Use a temporary canvas to convert named colors\n const ctx = document.createElement('canvas').getContext('2d')\n if (!ctx) {\n return { hex: '000000', alpha: 100, raw: name }\n }\n\n ctx.fillStyle = name\n const computed = ctx.fillStyle\n\n if (computed.startsWith('#')) {\n return parseHexColor(computed)\n }\n return parseRgbaColor(computed)\n}\n\nexport function parseColorValue(cssValue: string): ColorValue {\n const raw = cssValue.trim()\n\n // Handle transparent\n if (raw === 'transparent') {\n return { hex: '000000', alpha: 0, raw }\n }\n\n // Handle hex colors\n if (raw.startsWith('#')) {\n return parseHexColor(raw)\n }\n\n // Handle rgb/rgba\n if (raw.startsWith('rgb')) {\n return parseRgbaColor(raw)\n }\n\n // Fallback: use canvas to convert named colors\n return parseNamedColor(raw)\n}\n\nconst TRANSPARENT_COLOR: ColorValue = { hex: '000000', alpha: 0, raw: 'transparent' }\n\nfunction isVisibleBorderSide(side: { style: string; width: string }): boolean {\n return side.style !== 'none' && side.style !== 'hidden' && parseFloat(side.width) > 0\n}\n\nfunction hasVisibleOutline(computed: CSSStyleDeclaration): boolean {\n return computed.outlineStyle !== 'none' && parseFloat(computed.outlineWidth) > 0\n}\n\nfunction parseVisibleColor(\n value: string,\n fallbackCurrentColor?: string\n): ColorValue | null {\n const raw = value.trim()\n const lowered = raw.toLowerCase()\n if (!raw || lowered === 'none' || lowered === 'transparent') {\n return null\n }\n\n const resolved = /^currentcolor$/i.test(raw)\n ? (fallbackCurrentColor ?? raw)\n : raw\n const parsed = parseColorValue(resolved)\n if (parsed.alpha <= 0) {\n return null\n }\n return parsed\n}\n\nfunction addUniqueColor(\n colors: Map<string, ColorValue>,\n color: ColorValue | null\n): void {\n if (!color) return\n colors.set(`${color.hex}:${color.alpha}`, color)\n}\n\nfunction isTextRenderingFormControl(element: HTMLElement): boolean {\n if (element instanceof HTMLTextAreaElement) return true\n if (element instanceof HTMLSelectElement) return true\n if (element instanceof HTMLButtonElement) return true\n if (element instanceof HTMLInputElement) {\n const textlessInputTypes = new Set([\n 'hidden',\n 'checkbox',\n 'radio',\n 'range',\n 'color',\n 'file',\n 'image',\n ])\n return !textlessInputTypes.has(element.type.toLowerCase())\n }\n return false\n}\n\nfunction hasRenderableTextNode(element: HTMLElement): boolean {\n if (element.isContentEditable) return true\n if (isTextRenderingFormControl(element)) return true\n if (!element.textContent?.trim()) return false\n if (hasDirectNonWhitespaceText(element)) return true\n const tagName = element.tagName.toLowerCase()\n return TEXT_ELEMENT_TAGS.has(tagName) || element.children.length === 0\n}\n\nexport function getComputedBoxShadow(element: HTMLElement): string {\n const computed = window.getComputedStyle(element)\n const value = computed.boxShadow.trim()\n return value || 'none'\n}\n\nexport function getComputedColorStyles(element: HTMLElement): ColorProperties {\n const computed = window.getComputedStyle(element)\n\n const borderSides = [\n { style: computed.borderTopStyle, width: computed.borderTopWidth, color: computed.borderTopColor },\n { style: computed.borderRightStyle, width: computed.borderRightWidth, color: computed.borderRightColor },\n { style: computed.borderBottomStyle, width: computed.borderBottomWidth, color: computed.borderBottomColor },\n { style: computed.borderLeftStyle, width: computed.borderLeftWidth, color: computed.borderLeftColor },\n ]\n const visibleBorderSide = borderSides.find((side) => isVisibleBorderSide(side))\n const hasBorder = Boolean(visibleBorderSide)\n const hasOutline = hasVisibleOutline(computed)\n\n return {\n backgroundColor: parseColorValue(computed.backgroundColor),\n color: parseColorValue(computed.color),\n borderColor: hasBorder && visibleBorderSide ? parseColorValue(visibleBorderSide.color) : TRANSPARENT_COLOR,\n outlineColor: hasOutline ? parseColorValue(computed.outlineColor) : TRANSPARENT_COLOR,\n }\n}\n\nexport function getSelectionColors(element: HTMLElement): ColorValue[] {\n const uniqueColors = new Map<string, ColorValue>()\n const queue: Element[] = [element]\n\n for (let index = 0; index < queue.length; index++) {\n const node = queue[index]\n const computed = window.getComputedStyle(node)\n\n if (computed.display === 'none') {\n // Entire subtree is not rendered; skip traversal for performance.\n continue\n }\n\n const isVisibilityHidden =\n computed.visibility === 'hidden' || computed.visibility === 'collapse'\n const currentTextColor = computed.color\n\n if (!isVisibilityHidden) {\n addUniqueColor(uniqueColors, parseVisibleColor(computed.backgroundColor))\n\n if (node instanceof HTMLElement && hasRenderableTextNode(node)) {\n addUniqueColor(uniqueColors, parseVisibleColor(currentTextColor))\n }\n\n const borderSides = [\n { style: computed.borderTopStyle, width: computed.borderTopWidth, color: computed.borderTopColor },\n { style: computed.borderRightStyle, width: computed.borderRightWidth, color: computed.borderRightColor },\n { style: computed.borderBottomStyle, width: computed.borderBottomWidth, color: computed.borderBottomColor },\n { style: computed.borderLeftStyle, width: computed.borderLeftWidth, color: computed.borderLeftColor },\n ]\n for (const side of borderSides) {\n if (!isVisibleBorderSide(side)) continue\n addUniqueColor(uniqueColors, parseVisibleColor(side.color, currentTextColor))\n }\n\n if (hasVisibleOutline(computed)) {\n addUniqueColor(uniqueColors, parseVisibleColor(computed.outlineColor, currentTextColor))\n }\n\n if (node instanceof SVGElement) {\n const fillColor =\n parseVisibleColor(computed.getPropertyValue('fill'), currentTextColor)\n ?? parseVisibleColor(node.getAttribute('fill') ?? '', currentTextColor)\n const strokeColor =\n parseVisibleColor(computed.getPropertyValue('stroke'), currentTextColor)\n ?? parseVisibleColor(node.getAttribute('stroke') ?? '', currentTextColor)\n addUniqueColor(uniqueColors, fillColor)\n addUniqueColor(uniqueColors, strokeColor)\n }\n }\n\n for (const child of node.children) {\n queue.push(child)\n }\n }\n\n return Array.from(uniqueColors.values())\n}\n\nexport interface AllComputedStyles {\n spacing: SpacingProperties\n borderRadius: BorderRadiusProperties\n border: BorderProperties\n flex: FlexProperties\n sizing: SizingProperties\n color: ColorProperties\n boxShadow: string\n typography: TypographyProperties\n}\n\nexport function getAllComputedStyles(element: HTMLElement): AllComputedStyles {\n const { spacing, borderRadius, flex } = getComputedStyles(element)\n return {\n spacing,\n borderRadius,\n border: getComputedBorderStyles(element),\n flex,\n sizing: getComputedSizing(element),\n color: getComputedColorStyles(element),\n boxShadow: getComputedBoxShadow(element),\n typography: getComputedTypography(element),\n }\n}\n\nexport const colorPropertyToCSSMap: Record<ColorPropertyKey, string> = {\n backgroundColor: 'background-color',\n color: 'color',\n borderColor: 'border-color',\n outlineColor: 'outline-color',\n}\n\nconst colorTailwindPrefixMap: Record<ColorPropertyKey, string> = {\n backgroundColor: 'bg',\n color: 'text',\n borderColor: 'border',\n outlineColor: 'outline',\n}\n\nexport function colorToTailwind(\n property: ColorPropertyKey,\n colorValue: ColorValue\n): string {\n const prefix = colorTailwindPrefixMap[property]\n\n // Use arbitrary hex value\n if (colorValue.alpha === 100) {\n return `${prefix}-[#${colorValue.hex}]`\n }\n return `${prefix}-[#${colorValue.hex}]/${colorValue.alpha}`\n}\n\nexport function getElementInfo(element: HTMLElement): ElementInfo {\n const computed = window.getComputedStyle(element)\n const parentElement = element === document.body ? null : element.parentElement\n\n const isFlexContainer = computed.display === 'flex' || computed.display === 'inline-flex'\n\n let isFlexItem = false\n if (parentElement) {\n const parentComputed = window.getComputedStyle(parentElement)\n isFlexItem = parentComputed.display === 'flex' || parentComputed.display === 'inline-flex'\n }\n\n return {\n tagName: element.tagName.toLowerCase(),\n id: element.id || null,\n classList: Array.from(element.classList),\n isFlexContainer,\n isFlexItem,\n isTextElement: isTextElement(element),\n parentElement,\n hasChildren: element.children.length > 0,\n }\n}\n\ninterface DimensionDisplay {\n width: string\n height: string\n}\n\nfunction isFitSizing(element: HTMLElement, dimension: 'width' | 'height'): boolean {\n const computed = window.getComputedStyle(element)\n const inlineValue = element.style[dimension]\n\n if (inlineValue === 'auto') return true\n\n const computedValue = computed[dimension]\n\n if (!inlineValue) {\n const parent = element.parentElement\n if (parent) {\n const parentComputed = window.getComputedStyle(parent)\n if (parentComputed.display === 'flex' || parentComputed.display === 'inline-flex') {\n const flexBasis = computed.flexBasis\n const flexGrow = computed.flexGrow\n if (flexBasis === 'auto' && flexGrow === '0') {\n return true\n }\n }\n }\n\n if (dimension === 'width') {\n if (computed.display === 'block' && !inlineValue) {\n return false\n }\n if (\n computed.display === 'inline-block' ||\n computed.display === 'inline-flex' ||\n computed.display === 'inline'\n ) {\n return true\n }\n }\n\n if (dimension === 'height') {\n return !inlineValue\n }\n }\n\n if (computedValue.includes('fit-content') || computedValue.includes('max-content')) {\n return true\n }\n\n return false\n}\n\nexport function getDimensionDisplay(element: HTMLElement): DimensionDisplay {\n const width = Math.round(element.offsetWidth)\n const height = Math.round(element.offsetHeight)\n\n const widthIsFit = isFitSizing(element, 'width')\n const heightIsFit = isFitSizing(element, 'height')\n\n return {\n width: widthIsFit ? `Fit ${width}` : `${width}`,\n height: heightIsFit ? `Fit ${height}` : `${height}`,\n }\n}\n\n\nexport function calculateParentMeasurements(element: HTMLElement, container?: HTMLElement): MeasurementLine[] {\n const parent = container ?? element.parentElement\n if (!parent) return []\n\n const elementRect = element.getBoundingClientRect()\n const parentRect = parent.getBoundingClientRect()\n\n // Use clientLeft/clientTop for reliable border widths, clientWidth/clientHeight\n // for inner dimensions (handles scrollbars correctly)\n const paddingBoxLeft = parentRect.left + parent.clientLeft\n const paddingBoxTop = parentRect.top + parent.clientTop\n const paddingBoxRight = parentRect.left + parent.clientLeft + parent.clientWidth\n const paddingBoxBottom = parentRect.top + parent.clientTop + parent.clientHeight\n\n let parentInnerLeft: number\n let parentInnerTop: number\n let parentInnerRight: number\n let parentInnerBottom: number\n\n if (container) {\n // Ancestor case: measure from padding-box (inside border, outside padding).\n // The ancestor's padding doesn't directly position the child — intermediate\n // elements do — so the visually correct edge is inside the border only.\n parentInnerLeft = paddingBoxLeft\n parentInnerTop = paddingBoxTop\n parentInnerRight = paddingBoxRight\n parentInnerBottom = paddingBoxBottom\n } else {\n // Direct parent case: measure from content-box (inside border and padding).\n // The parent's padding IS the gap between its edge and the child's layout area.\n const parentStyles = window.getComputedStyle(parent)\n parentInnerLeft = paddingBoxLeft + (parseFloat(parentStyles.paddingLeft) || 0)\n parentInnerTop = paddingBoxTop + (parseFloat(parentStyles.paddingTop) || 0)\n parentInnerRight = paddingBoxRight - (parseFloat(parentStyles.paddingRight) || 0)\n parentInnerBottom = paddingBoxBottom - (parseFloat(parentStyles.paddingBottom) || 0)\n }\n\n const zoom = getZoomScale()\n const measurements: MeasurementLine[] = []\n\n const topDistance = Math.round((elementRect.top - parentInnerTop) / zoom)\n if (topDistance > 0) {\n const midX = elementRect.left + elementRect.width / 2\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: parentInnerTop,\n x2: midX,\n y2: elementRect.top,\n distance: topDistance,\n labelPosition: { x: midX, y: (parentInnerTop + elementRect.top) / 2 },\n })\n }\n\n const bottomDistance = Math.round((parentInnerBottom - elementRect.bottom) / zoom)\n if (bottomDistance > 0) {\n const midX = elementRect.left + elementRect.width / 2\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: elementRect.bottom,\n x2: midX,\n y2: parentInnerBottom,\n distance: bottomDistance,\n labelPosition: { x: midX, y: (elementRect.bottom + parentInnerBottom) / 2 },\n })\n }\n\n const leftDistance = Math.round((elementRect.left - parentInnerLeft) / zoom)\n if (leftDistance > 0) {\n const midY = elementRect.top + elementRect.height / 2\n measurements.push({\n direction: 'horizontal',\n x1: parentInnerLeft,\n y1: midY,\n x2: elementRect.left,\n y2: midY,\n distance: leftDistance,\n labelPosition: { x: (parentInnerLeft + elementRect.left) / 2, y: midY },\n })\n }\n\n const rightDistance = Math.round((parentInnerRight - elementRect.right) / zoom)\n if (rightDistance > 0) {\n const midY = elementRect.top + elementRect.height / 2\n measurements.push({\n direction: 'horizontal',\n x1: elementRect.right,\n y1: midY,\n x2: parentInnerRight,\n y2: midY,\n distance: rightDistance,\n labelPosition: { x: (elementRect.right + parentInnerRight) / 2, y: midY },\n })\n }\n\n return measurements\n}\n\nexport function calculateElementMeasurements(\n from: HTMLElement,\n to: HTMLElement\n): MeasurementLine[] {\n const fromRect = from.getBoundingClientRect()\n const toRect = to.getBoundingClientRect()\n const zoom = getZoomScale()\n const measurements: MeasurementLine[] = []\n\n const horizontalOverlap =\n fromRect.left < toRect.right && fromRect.right > toRect.left\n const verticalOverlap =\n fromRect.top < toRect.bottom && fromRect.bottom > toRect.top\n\n if (verticalOverlap) {\n const overlapTop = Math.max(fromRect.top, toRect.top)\n const overlapBottom = Math.min(fromRect.bottom, toRect.bottom)\n const midY = (overlapTop + overlapBottom) / 2\n\n if (fromRect.right <= toRect.left) {\n const distance = Math.round((toRect.left - fromRect.right) / zoom)\n measurements.push({\n direction: 'horizontal',\n x1: fromRect.right,\n y1: midY,\n x2: toRect.left,\n y2: midY,\n distance,\n labelPosition: { x: (fromRect.right + toRect.left) / 2, y: midY },\n })\n } else if (fromRect.left >= toRect.right) {\n const distance = Math.round((fromRect.left - toRect.right) / zoom)\n measurements.push({\n direction: 'horizontal',\n x1: toRect.right,\n y1: midY,\n x2: fromRect.left,\n y2: midY,\n distance,\n labelPosition: { x: (toRect.right + fromRect.left) / 2, y: midY },\n })\n }\n }\n\n if (horizontalOverlap) {\n const overlapLeft = Math.max(fromRect.left, toRect.left)\n const overlapRight = Math.min(fromRect.right, toRect.right)\n const midX = (overlapLeft + overlapRight) / 2\n\n if (fromRect.bottom <= toRect.top) {\n const distance = Math.round((toRect.top - fromRect.bottom) / zoom)\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: fromRect.bottom,\n x2: midX,\n y2: toRect.top,\n distance,\n labelPosition: { x: midX, y: (fromRect.bottom + toRect.top) / 2 },\n })\n } else if (fromRect.top >= toRect.bottom) {\n const distance = Math.round((fromRect.top - toRect.bottom) / zoom)\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: toRect.bottom,\n x2: midX,\n y2: fromRect.top,\n distance,\n labelPosition: { x: midX, y: (toRect.bottom + fromRect.top) / 2 },\n })\n }\n }\n\n if (!horizontalOverlap && !verticalOverlap) {\n const fromCenterX = fromRect.left + fromRect.width / 2\n const fromCenterY = fromRect.top + fromRect.height / 2\n const toCenterX = toRect.left + toRect.width / 2\n const toCenterY = toRect.top + toRect.height / 2\n\n const hDistance = toCenterX > fromCenterX\n ? Math.round((toRect.left - fromRect.right) / zoom)\n : Math.round((fromRect.left - toRect.right) / zoom)\n\n if (hDistance > 0) {\n const startX = toCenterX > fromCenterX ? fromRect.right : fromRect.left\n const endX = toCenterX > fromCenterX ? toRect.left : toRect.right\n const y = (fromCenterY + toCenterY) / 2\n measurements.push({\n direction: 'horizontal',\n x1: startX,\n y1: y,\n x2: endX,\n y2: y,\n distance: hDistance,\n labelPosition: { x: (startX + endX) / 2, y },\n })\n }\n\n const vDistance = toCenterY > fromCenterY\n ? Math.round((toRect.top - fromRect.bottom) / zoom)\n : Math.round((fromRect.top - toRect.bottom) / zoom)\n\n if (vDistance > 0) {\n const x = (fromCenterX + toCenterX) / 2\n const startY = toCenterY > fromCenterY ? fromRect.bottom : fromRect.top\n const endY = toCenterY > fromCenterY ? toRect.top : toRect.bottom\n measurements.push({\n direction: 'vertical',\n x1: x,\n y1: startY,\n x2: x,\n y2: endY,\n distance: vDistance,\n labelPosition: { x, y: (startY + endY) / 2 },\n })\n }\n }\n\n return measurements\n}\n\nconst GUIDELINE_PROXIMITY = 80\n\nexport function calculateGuidelineMeasurements(\n element: HTMLElement,\n guidelines: Guideline[],\n mousePosition?: { x: number; y: number } | null,\n): MeasurementLine[] {\n if (guidelines.length === 0) return []\n\n const snap = getCanvasSnapshot()\n const zoom = snap.active ? snap.zoom : 1\n const rect = element.getBoundingClientRect()\n const measurements: MeasurementLine[] = []\n\n for (const g of guidelines) {\n let viewportPos: number\n if (snap.active) {\n const pan = g.orientation === 'horizontal' ? snap.panY : snap.panX\n const bo = g.orientation === 'horizontal' ? getBodyOffset().y : getBodyOffset().x\n viewportPos = bo + (g.position - bo + pan) * zoom\n } else {\n const scroll = g.orientation === 'horizontal' ? window.scrollY : window.scrollX\n viewportPos = g.position - scroll\n }\n\n if (g.orientation === 'horizontal') {\n const midX = rect.left + rect.width / 2\n\n if (mousePosition && Math.abs(mousePosition.y - viewportPos) > GUIDELINE_PROXIMITY) continue\n\n if (viewportPos < rect.top) {\n const distance = Math.round((rect.top - viewportPos) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: viewportPos,\n x2: midX,\n y2: rect.top,\n distance,\n labelPosition: { x: midX, y: (viewportPos + rect.top) / 2 },\n })\n }\n } else if (viewportPos > rect.bottom) {\n const distance = Math.round((viewportPos - rect.bottom) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: rect.bottom,\n x2: midX,\n y2: viewportPos,\n distance,\n labelPosition: { x: midX, y: (rect.bottom + viewportPos) / 2 },\n })\n }\n }\n } else {\n const midY = rect.top + rect.height / 2\n\n if (mousePosition && Math.abs(mousePosition.x - viewportPos) > GUIDELINE_PROXIMITY) continue\n\n if (viewportPos < rect.left) {\n const distance = Math.round((rect.left - viewportPos) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'horizontal',\n x1: viewportPos,\n y1: midY,\n x2: rect.left,\n y2: midY,\n distance,\n labelPosition: { x: (viewportPos + rect.left) / 2, y: midY },\n })\n }\n } else if (viewportPos > rect.right) {\n const distance = Math.round((viewportPos - rect.right) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'horizontal',\n x1: rect.right,\n y1: midY,\n x2: viewportPos,\n y2: midY,\n distance,\n labelPosition: { x: (rect.right + viewportPos) / 2, y: midY },\n })\n }\n }\n }\n }\n\n return measurements\n}\n\nexport function isFlexContainer(element: HTMLElement): boolean {\n const computed = window.getComputedStyle(element)\n return computed.display === 'flex' || computed.display === 'inline-flex'\n}\n\nexport function getFlexDirection(\n element: HTMLElement\n): 'row' | 'row-reverse' | 'column' | 'column-reverse' {\n const computed = window.getComputedStyle(element)\n return computed.flexDirection as 'row' | 'row-reverse' | 'column' | 'column-reverse'\n}\n\n/** True when the child participates in normal flow (not hidden, absolute, or fixed). */\nexport function isInFlowChild(el: HTMLElement): boolean {\n const cs = window.getComputedStyle(el)\n return cs.display !== 'none' && cs.position !== 'absolute' && cs.position !== 'fixed'\n}\n\nexport function detectChildrenDirection(\n container: HTMLElement,\n exclude: HTMLElement | null\n): { axis: 'horizontal' | 'vertical'; reversed: boolean } {\n const computed = window.getComputedStyle(container)\n\n // Flex: trust CSS for accuracy (especially reverse)\n if (computed.display === 'flex' || computed.display === 'inline-flex') {\n const dir = computed.flexDirection\n return {\n axis: (dir === 'row' || dir === 'row-reverse') ? 'horizontal' : 'vertical',\n reversed: dir === 'row-reverse' || dir === 'column-reverse',\n }\n }\n\n // Non-flex: examine first two visible, in-flow children\n const visible: HTMLElement[] = []\n for (const c of container.children) {\n if (!(c instanceof HTMLElement) || c === exclude) continue\n if (!isInFlowChild(c)) continue\n visible.push(c)\n if (visible.length === 2) break\n }\n\n if (visible.length < 2) return { axis: 'vertical', reversed: false }\n\n const first = visible[0].getBoundingClientRect()\n const second = visible[1].getBoundingClientRect()\n const yOverlap = first.bottom - 2 > second.top && second.bottom - 2 > first.top\n\n if (yOverlap) {\n return { axis: 'horizontal', reversed: second.right < first.left }\n }\n return { axis: 'vertical', reversed: second.bottom < first.top }\n}\n\nexport function computeIntendedIndex(\n parent: HTMLElement,\n draggedElement: HTMLElement,\n): {\n index: number\n siblingBefore: HTMLElement | null\n siblingAfter: HTMLElement | null\n} {\n const { axis } = detectChildrenDirection(parent, draggedElement)\n const isHorizontal = axis === 'horizontal'\n const draggedRect = draggedElement.getBoundingClientRect()\n const intendedCenter = isHorizontal\n ? draggedRect.left + draggedRect.width / 2\n : draggedRect.top + draggedRect.height / 2\n\n const siblings: HTMLElement[] = []\n for (const c of parent.children) {\n if (!(c instanceof HTMLElement) || c === draggedElement) continue\n if (!isInFlowChild(c)) continue\n siblings.push(c)\n }\n\n if (siblings.length === 0) {\n return { index: 0, siblingBefore: null, siblingAfter: null }\n }\n\n for (let i = 0; i < siblings.length; i++) {\n const rect = siblings[i].getBoundingClientRect()\n const midpoint = isHorizontal\n ? rect.left + rect.width / 2\n : rect.top + rect.height / 2\n if (intendedCenter < midpoint) {\n return { index: i, siblingBefore: i > 0 ? siblings[i - 1] : null, siblingAfter: siblings[i] }\n }\n }\n\n return { index: siblings.length, siblingBefore: siblings[siblings.length - 1], siblingAfter: null }\n}\n\nfunction htmlChildren(el: HTMLElement): HTMLElement[] {\n return Array.from(el.children).filter(\n (child): child is HTMLElement => child instanceof HTMLElement\n )\n}\n\n/** Walk up from `element` to find the nearest flex/inline-flex ancestor, stopping at `boundary`. */\nfunction findFlexAncestor(\n element: HTMLElement,\n boundary: HTMLElement | null,\n): { flexParent: HTMLElement; child: HTMLElement } | null {\n let current: HTMLElement | null = element\n while (current && current !== document.body) {\n const parent: HTMLElement | null = current.parentElement\n if (!parent) break\n const display = getComputedStyle(parent).display\n if (display === 'flex' || display === 'inline-flex') {\n return { flexParent: parent, child: current }\n }\n if (boundary && parent === boundary) break\n current = parent\n }\n return null\n}\n\nexport function computeHoverHighlight(\n elementUnder: HTMLElement | null,\n selectedElement: HTMLElement | null,\n): { flexContainer: HTMLElement; children: HTMLElement[] } | null {\n if (\n !elementUnder ||\n elementUnder === document.body ||\n elementUnder === document.documentElement ||\n elementUnder.closest('[data-direct-edit]') ||\n elementUnder.closest('[data-direct-edit-host]') ||\n elementUnder === selectedElement\n ) {\n return null\n }\n\n // When hovering descendants of the selected element, stop walk-up at the boundary\n const boundary = selectedElement?.contains(elementUnder) ? selectedElement : null\n\n const ownDisplay = getComputedStyle(elementUnder).display\n if (ownDisplay === 'flex' || ownDisplay === 'inline-flex') {\n return { flexContainer: elementUnder, children: htmlChildren(elementUnder) }\n }\n\n const found = findFlexAncestor(elementUnder, boundary)\n if (found) {\n return { flexContainer: found.flexParent, children: htmlChildren(found.flexParent) }\n }\n\n return { flexContainer: elementUnder, children: [] }\n}\n\nexport function resolveElementTarget(\n elementUnder: HTMLElement,\n selectedElement: HTMLElement | null,\n): HTMLElement {\n const boundary = selectedElement?.contains(elementUnder) ? selectedElement : null\n const found = findFlexAncestor(elementUnder, boundary)\n if (found && found.flexParent === boundary) return elementUnder\n return found?.child ?? elementUnder\n}\n\n/** Finds the text-owning element at a point within `boundary` using browser caret hit-testing. */\nexport function findTextOwnerAtPoint(\n boundary: HTMLElement,\n clientX: number,\n clientY: number,\n): HTMLElement | null {\n const doc = document as Document & {\n caretPositionFromPoint?: (x: number, y: number) => { offsetNode: Node } | null\n caretRangeFromPoint?: (x: number, y: number) => Range | null\n }\n\n const caretNode =\n doc.caretPositionFromPoint?.(clientX, clientY)?.offsetNode\n ?? doc.caretRangeFromPoint?.(clientX, clientY)?.startContainer\n ?? null\n if (!caretNode || caretNode.nodeType !== Node.TEXT_NODE) return null\n\n const textNode = caretNode as Text\n if (!(textNode.nodeValue ?? '').trim()) return null\n\n const owner = textNode.parentElement\n if (!owner || !boundary.contains(owner)) return null\n if (owner.closest('[data-direct-edit]') || owner.closest('[data-direct-edit-host]')) return null\n\n // Guard against caret APIs returning nearby text nodes.\n const range = document.createRange()\n range.selectNodeContents(textNode)\n const hitsText = Array.from(range.getClientRects()).some(\n (r) => clientX >= r.left && clientX <= r.right && clientY >= r.top && clientY <= r.bottom\n )\n range.detach?.()\n return hitsText ? owner : null\n}\n\n/** Fallback text hit-testing by scanning text nodes and rendered rects within `boundary`. */\nexport function findTextOwnerByRangeScan(\n boundary: HTMLElement,\n clientX: number,\n clientY: number,\n): HTMLElement | null {\n const walker = document.createTreeWalker(boundary, NodeFilter.SHOW_TEXT)\n let current: Node | null = walker.nextNode()\n\n while (current) {\n const textNode = current as Text\n if ((textNode.nodeValue ?? '').trim()) {\n const owner = textNode.parentElement\n if (\n owner &&\n boundary.contains(owner) &&\n !owner.closest('[data-direct-edit]') &&\n !owner.closest('[data-direct-edit-host]')\n ) {\n const range = document.createRange()\n range.selectNodeContents(textNode)\n const hitsText = Array.from(range.getClientRects()).some(\n (r) => clientX >= r.left && clientX <= r.right && clientY >= r.top && clientY <= r.bottom\n )\n range.detach?.()\n if (hitsText) return owner\n }\n }\n current = walker.nextNode()\n }\n\n return null\n}\n\n/** Wrap the direct text node under the point into a span so it becomes independently selectable. */\nexport function ensureDirectTextSpanAtPoint(\n parent: HTMLElement,\n clientX: number,\n clientY: number,\n): HTMLElement | null {\n const directTextNodes = Array.from(parent.childNodes).filter(\n (node): node is Text => node.nodeType === Node.TEXT_NODE && Boolean(node.textContent?.trim())\n )\n\n for (const textNode of directTextNodes) {\n const range = document.createRange()\n range.selectNodeContents(textNode)\n const hitsText = Array.from(range.getClientRects()).some(\n (r) => clientX >= r.left && clientX <= r.right && clientY >= r.top && clientY <= r.bottom\n )\n range.detach?.()\n\n if (!hitsText) continue\n\n const span = document.createElement('span')\n span.setAttribute('data-direct-edit-generated', 'text-span')\n span.textContent = textNode.textContent ?? ''\n parent.replaceChild(span, textNode)\n return span\n }\n\n return null\n}\n\n/** When elementFromPoint returns the selected element (bare text, padding, gap),\n * find the best child element to drill into at the given coordinates. */\nexport function findChildAtPoint(\n parent: HTMLElement,\n clientX: number,\n clientY: number,\n): HTMLElement | null {\n const children = htmlChildren(parent)\n if (children.length === 0) return null\n\n // Direct hit: child whose bbox contains the click\n const hit = children.find((child) => {\n const r = child.getBoundingClientRect()\n return clientX >= r.left && clientX <= r.right && clientY >= r.top && clientY <= r.bottom\n })\n if (hit) return hit\n\n // Single-child fallback should not steal clicks from parent's direct text.\n if (children.length === 1 && !hasDirectNonWhitespaceText(parent)) return children[0]\n\n return null\n}\n\nexport function elementFromPointWithoutOverlays(x: number, y: number): HTMLElement | null {\n const host = document.querySelector<HTMLElement>('[data-direct-edit-host]')\n if (host) host.style.display = 'none'\n const el = document.elementFromPoint(x, y) as HTMLElement | null\n if (host) host.style.display = ''\n return el\n}\n\nexport function isLayoutContainer(element: HTMLElement): boolean {\n const display = window.getComputedStyle(element).display\n return (\n display === 'flex' ||\n display === 'inline-flex' ||\n display === 'grid' ||\n display === 'inline-grid'\n )\n}\n\nfunction isBlockContainer(element: HTMLElement): boolean {\n const display = window.getComputedStyle(element).display\n return display === 'block' || display === 'flow-root'\n || display === 'inline-block' || display === 'list-item'\n}\n\nfunction skipElement(el: HTMLElement, exclude: HTMLElement | null): boolean {\n if (exclude && exclude.contains(el)) return true\n if (el === document.body || el === document.documentElement) return true\n if (el.closest('[data-direct-edit]') || el.closest('[data-direct-edit-host]')) return true\n return false\n}\n\nfunction findContainerViaTraversal(x: number, y: number, exclude: HTMLElement | null): HTMLElement | null {\n const el = elementFromPointWithoutOverlays(x, y)\n if (!el) return null\n let current: HTMLElement | null = el\n while (current) {\n if (!skipElement(current, exclude)) {\n if (isLayoutContainer(current) || isBlockContainer(current)) return current\n }\n current = current.parentElement\n }\n return null\n}\n\nexport function findContainerAtPoint(\n x: number,\n y: number,\n exclude: HTMLElement | null,\n preferredParent?: HTMLElement | null\n): HTMLElement | null {\n const host = document.querySelector<HTMLElement>('[data-direct-edit-host]')\n if (host) host.style.display = 'none'\n\n const elements = document.elementsFromPoint(x, y) as HTMLElement[]\n\n if (host) host.style.display = ''\n\n // Find most specific container (front-to-back = most nested first)\n for (const el of elements) {\n if (skipElement(el, exclude)) continue\n if (isLayoutContainer(el) || isBlockContainer(el)) return el\n }\n\n // Fallback: preferredParent for gap/padding areas\n if (preferredParent && (isLayoutContainer(preferredParent) || isBlockContainer(preferredParent))) {\n for (const el of elements) {\n if (el === preferredParent) return preferredParent\n }\n }\n\n // Last resort: walk up DOM\n return findContainerViaTraversal(x, y, exclude)\n}\n\nexport function findLayoutContainerAtPoint(\n x: number,\n y: number,\n exclude: HTMLElement | null,\n preferredParent?: HTMLElement | null,\n): HTMLElement | null {\n const host = document.querySelector<HTMLElement>('[data-direct-edit-host]')\n if (host) host.style.display = 'none'\n const elements = document.elementsFromPoint(x, y) as HTMLElement[]\n if (host) host.style.display = ''\n\n for (const el of elements) {\n if (skipElement(el, exclude)) continue\n if (isLayoutContainer(el)) return el\n }\n\n if (preferredParent && isLayoutContainer(preferredParent)) {\n for (const el of elements) {\n if (el === preferredParent) return preferredParent\n }\n }\n\n return null\n}\n\nexport function calculateDropPosition(\n container: HTMLElement,\n pointerX: number,\n pointerY: number,\n draggedElement: HTMLElement\n): { insertBefore: HTMLElement | null; indicator: DropIndicator } | null {\n const { axis, reversed: isReversed } = detectChildrenDirection(container, draggedElement)\n const isHorizontal = axis === 'horizontal'\n\n const children = Array.from(container.children).filter(\n (child) => child !== draggedElement && child instanceof HTMLElement\n ) as HTMLElement[]\n\n if (children.length === 0) {\n const containerRect = container.getBoundingClientRect()\n return {\n insertBefore: null,\n indicator: {\n x: containerRect.left + 4,\n y: containerRect.top + 4,\n width: isHorizontal ? 1 : containerRect.width - 8,\n height: isHorizontal ? containerRect.height - 8 : 1,\n },\n }\n }\n\n const containerRect = container.getBoundingClientRect()\n let insertBefore: HTMLElement | null = null\n let indicatorPosition = 0\n\n for (let i = 0; i < children.length; i++) {\n const child = children[i]\n const rect = child.getBoundingClientRect()\n const midpoint = isHorizontal\n ? rect.left + rect.width / 2\n : rect.top + rect.height / 2\n\n const pointer = isHorizontal ? pointerX : pointerY\n\n const beforeMidpoint = isReversed ? pointer > midpoint : pointer < midpoint\n\n if (beforeMidpoint) {\n insertBefore = child\n indicatorPosition = isHorizontal ? rect.left : rect.top\n break\n }\n }\n\n if (!insertBefore) {\n const lastChild = children[children.length - 1]\n const lastRect = lastChild.getBoundingClientRect()\n indicatorPosition = isHorizontal ? lastRect.right : lastRect.bottom\n }\n\n const indicator: DropIndicator = isHorizontal\n ? {\n x: indicatorPosition,\n y: containerRect.top + 4,\n width: 2,\n height: containerRect.height - 8,\n }\n : {\n x: containerRect.left + 4,\n y: indicatorPosition,\n width: containerRect.width - 8,\n height: 2,\n }\n\n return { insertBefore, indicator }\n}\n\n// Accesses React fiber internals to find the component stack. This is an undocumented\n// API that could change between React versions, but is a common pattern for dev tools.\n// Returns an empty array gracefully if React internals are unavailable.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getFiberForElement(element: HTMLElement): any | null {\n if (typeof window !== 'undefined') {\n const devtools = window.__DIRECT_EDIT_DEVTOOLS__\n if (devtools?.getFiberForElement) {\n const fiber = devtools.getFiberForElement(element)\n if (fiber) return fiber as any\n }\n }\n\n const fiberKey = Object.keys(element).find(\n (key) => key.startsWith('__reactFiber$') || key.startsWith('__reactInternalInstance$')\n )\n\n if (!fiberKey) return null\n return (element as any)[fiberKey] || null\n}\n\ntype ParsedStackFrame = {\n functionName?: string\n fileName?: string\n lineNumber?: number\n columnNumber?: number\n source?: string\n isServer?: boolean\n}\n\nconst STACK_SOURCE_FILE_EXTENSION_REGEX = /\\.(jsx|tsx|ts|js)$/\nconst STACK_BUNDLED_FILE_PATTERN_REGEX =\n /(\\.min|bundle|chunk|vendor|vendors|runtime|polyfill|polyfills)\\.(js|mjs|cjs)$|(chunk|bundle|vendor|vendors|runtime|polyfill|polyfills|framework|app|main|index)[-_.][A-Za-z0-9_-]{4,}\\.(js|mjs|cjs)$|[\\da-f]{8,}\\.(js|mjs|cjs)$|[-_.][\\da-f]{20,}\\.(js|mjs|cjs)$|\\/dist\\/|\\/build\\/|\\/.next\\/|\\/out\\/|\\/node_modules\\/|\\.webpack\\.|\\.vite\\.|\\.turbopack\\./i\nconst FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\\S+:\\d+/\nconst SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\\[native code\\])?$/\nconst SERVER_FRAME_MARKER = '(at Server)'\n\nconst STACK_INTERNAL_SCHEME_PREFIXES = [\n 'rsc://',\n 'about://React/',\n 'React/Server/',\n 'file:///',\n 'webpack://',\n 'webpack-internal://',\n 'node:',\n 'turbopack://',\n '/app-pages-browser/',\n] as const\n\nfunction formatOwnerDebugStack(stack: string): string {\n if (!stack) return ''\n\n const lines = stack.split('\\n')\n const filtered: string[] = []\n\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed) continue\n if (trimmed === 'Error: react-stack-top-frame') continue\n if (\n trimmed.includes('react_stack_bottom_frame') ||\n trimmed.includes('react-stack-bottom-frame')\n ) {\n continue\n }\n filtered.push(line)\n }\n\n if (filtered.length > 0 && filtered[0].includes('fakeJSXCallSite')) {\n filtered.shift()\n }\n\n return filtered.join('\\n')\n}\n\nfunction extractStackLocation(urlLike: string): [string, number | undefined, number | undefined] {\n if (!urlLike.includes(':')) return [urlLike, undefined, undefined]\n\n const isWrappedLocation = urlLike.startsWith('(') && /:\\d+\\)$/.test(urlLike)\n const sanitizedResult = isWrappedLocation ? urlLike.slice(1, -1) : urlLike\n const parts = /(.+?)(?::(\\d+))?(?::(\\d+))?$/.exec(sanitizedResult)\n if (!parts) return [sanitizedResult, undefined, undefined]\n\n return [\n parts[1],\n parts[2] !== undefined ? Number(parts[2]) : undefined,\n parts[3] !== undefined ? Number(parts[3]) : undefined,\n ]\n}\n\nfunction parseV8StackLine(line: string): ParsedStackFrame | null {\n let currentLine = line\n if (currentLine.includes('(eval ')) {\n currentLine = currentLine\n .replace(/eval code/g, 'eval')\n .replace(/(\\(eval at [^()]*)|(,.*$)/g, '')\n }\n\n let sanitizedLine = currentLine\n .replace(/^\\s+/, '')\n .replace(/\\(eval code/g, '(')\n .replace(/^.*?\\s+/, '')\n const locationMatch = sanitizedLine.match(/ (\\(.+\\)$)/)\n if (locationMatch) {\n sanitizedLine = sanitizedLine.replace(locationMatch[0], '')\n }\n\n const [fileName, lineNumber, columnNumber] = extractStackLocation(\n locationMatch ? locationMatch[1] : sanitizedLine\n )\n const functionName = locationMatch && sanitizedLine ? sanitizedLine : undefined\n if (fileName === 'eval' || fileName === '<anonymous>') {\n return {\n functionName,\n }\n }\n\n return {\n functionName,\n fileName,\n lineNumber,\n columnNumber,\n source: currentLine,\n isServer: currentLine.includes(SERVER_FRAME_MARKER) || fileName.startsWith('rsc://'),\n }\n}\n\nfunction parseFFOrSafariStackLine(line: string): ParsedStackFrame | null {\n let currentLine = line\n if (currentLine.includes(' > eval')) {\n currentLine = currentLine.replace(\n / line (\\d+)(?: > eval line \\d+)* > eval:\\d+:\\d+/g,\n ':$1'\n )\n }\n\n const trimmed = currentLine.trim()\n if (!trimmed || SAFARI_NATIVE_CODE_REGEXP.test(trimmed)) {\n return null\n }\n\n if (!trimmed.includes('@') && !trimmed.includes(':')) {\n return {\n functionName: trimmed,\n source: currentLine,\n isServer: trimmed.includes(SERVER_FRAME_MARKER),\n }\n }\n\n const atIndex = trimmed.lastIndexOf('@')\n if (atIndex === -1) {\n return null\n }\n const maybeFunctionName = trimmed.slice(0, atIndex)\n const location = trimmed.slice(atIndex + 1)\n const [fileName, lineNumber, columnNumber] = extractStackLocation(location)\n\n return {\n functionName: maybeFunctionName || undefined,\n fileName,\n lineNumber,\n columnNumber,\n source: currentLine,\n isServer: currentLine.includes(SERVER_FRAME_MARKER) || fileName.startsWith('rsc://'),\n }\n}\n\nfunction parseInStackLine(line: string): ParsedStackFrame | null {\n const functionName = line\n .replace(/^\\s*in\\s+/, '')\n .replace(/\\s*\\(at .*\\)$/, '')\n .trim()\n if (!functionName) return null\n\n return {\n functionName,\n source: line,\n isServer: line.includes(SERVER_FRAME_MARKER),\n }\n}\n\nfunction parseDebugStack(stack: string): ParsedStackFrame[] {\n const frames: ParsedStackFrame[] = []\n for (const rawLine of stack.split('\\n')) {\n if (FIREFOX_SAFARI_STACK_REGEXP.test(rawLine)) {\n const parsed = parseFFOrSafariStackLine(rawLine)\n if (parsed) frames.push(parsed)\n continue\n }\n\n if (/^\\s*at\\s+/.test(rawLine)) {\n const parsed = parseV8StackLine(rawLine)\n if (parsed) frames.push(parsed)\n continue\n }\n\n if (/^\\s*in\\s+/.test(rawLine)) {\n const parsed = parseInStackLine(rawLine)\n if (parsed) frames.push(parsed)\n }\n }\n\n return frames\n}\n\nfunction normalizeStackFileName(fileName: string): string {\n if (!fileName) return ''\n\n let normalized = fileName\n const isHttpUrl = normalized.startsWith('http://') || normalized.startsWith('https://')\n if (isHttpUrl) {\n try {\n normalized = new URL(normalized).pathname\n } catch {\n // Fall through and use the original string.\n }\n }\n\n let didStripPrefix = true\n while (didStripPrefix) {\n didStripPrefix = false\n for (const prefix of STACK_INTERNAL_SCHEME_PREFIXES) {\n if (normalized.startsWith(prefix)) {\n normalized = normalized.slice(prefix.length)\n if (prefix === 'file:///') {\n normalized = `/${normalized.replace(/^\\/+/, '')}`\n }\n didStripPrefix = true\n break\n }\n }\n }\n\n normalized = normalized\n .replace(/^\\/\\(app-pages-browser\\)\\//, '/')\n .replace(/^\\/\\.\\//, '/')\n .replace(/^\\.\\//, '')\n\n const queryIndex = normalized.indexOf('?')\n if (queryIndex !== -1) {\n normalized = normalized.slice(0, queryIndex)\n }\n\n return normalized\n}\n\nfunction isSourceStackFile(fileName: string): boolean {\n const normalizedFileName = normalizeStackFileName(fileName)\n if (!normalizedFileName) return false\n if (!STACK_SOURCE_FILE_EXTENSION_REGEX.test(normalizedFileName)) return false\n return !STACK_BUNDLED_FILE_PATTERN_REGEX.test(normalizedFileName)\n}\n\ntype EnrichedServerFrame = {\n fileName: string\n lineNumber?: number\n columnNumber?: number\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction buildFunctionNameToRscFramesMap(fiber: any): Map<string, EnrichedServerFrame[]> {\n const functionNameToRscFrames = new Map<string, EnrichedServerFrame[]>()\n const visited = new Set<any>()\n let current = fiber\n\n while (current && !visited.has(current)) {\n visited.add(current)\n const rawStack = current?._debugStack?.stack\n const stack = typeof rawStack === 'string' ? formatOwnerDebugStack(rawStack) : ''\n if (stack) {\n const frames = parseDebugStack(stack)\n for (const frame of frames) {\n if (!frame.functionName || !frame.fileName) continue\n if (!frame.fileName.startsWith('rsc://')) continue\n\n const normalized = normalizeStackFileName(frame.fileName)\n if (!normalized) continue\n\n const existing = functionNameToRscFrames.get(frame.functionName) ?? []\n const duplicate = existing.some(\n (candidate) =>\n candidate.fileName === normalized &&\n candidate.lineNumber === frame.lineNumber &&\n candidate.columnNumber === frame.columnNumber\n )\n if (!duplicate) {\n existing.push({\n fileName: normalized,\n lineNumber: frame.lineNumber,\n columnNumber: frame.columnNumber,\n })\n functionNameToRscFrames.set(frame.functionName, existing)\n }\n }\n }\n\n current = current._debugOwner ?? current.return ?? null\n }\n\n return functionNameToRscFrames\n}\n\nfunction enrichServerFrame(\n frame: ParsedStackFrame,\n functionNameToRscFrames: Map<string, EnrichedServerFrame[]>,\n functionNameToUsageIndex: Map<string, number>,\n): ParsedStackFrame {\n if (!frame.functionName) return frame\n\n const available = functionNameToRscFrames.get(frame.functionName)\n if (!available) return frame\n\n const usageIndex = functionNameToUsageIndex.get(frame.functionName) ?? 0\n const resolved = available[usageIndex % available.length]\n functionNameToUsageIndex.set(frame.functionName, usageIndex + 1)\n\n return {\n ...frame,\n fileName: resolved.fileName,\n lineNumber: resolved.lineNumber,\n columnNumber: resolved.columnNumber,\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getSourceFromDebugStack(fiber: any):\n | {\n fileName?: string\n lineNumber?: number\n columnNumber?: number\n }\n | null {\n const rawStack = fiber?._debugStack?.stack\n if (typeof rawStack !== 'string' || rawStack.length === 0) {\n return null\n }\n\n const formattedStack = formatOwnerDebugStack(rawStack)\n if (!formattedStack) return null\n\n const stackFrames = parseDebugStack(formattedStack)\n const functionNameToRscFrames = buildFunctionNameToRscFramesMap(fiber)\n const functionNameToUsageIndex = new Map<string, number>()\n\n for (const frame of stackFrames) {\n const maybeEnriched = frame.isServer\n ? enrichServerFrame(frame, functionNameToRscFrames, functionNameToUsageIndex)\n : frame\n if (!maybeEnriched.fileName) continue\n\n const normalizedFileName = normalizeStackFileName(maybeEnriched.fileName)\n if (!normalizedFileName) continue\n\n if (isSourceStackFile(normalizedFileName)) {\n return {\n fileName: normalizedFileName,\n lineNumber: maybeEnriched.lineNumber,\n columnNumber: maybeEnriched.columnNumber,\n }\n }\n }\n\n return null\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getSourceFromFiber(fiber: any):\n | {\n fileName?: string\n lineNumber?: number\n columnNumber?: number\n }\n | null {\n const debugSource = fiber?._debugSource\n if (debugSource?.fileName) return debugSource\n\n const owner = fiber?._debugOwner\n const ownerPending = owner?.pendingProps?.__source\n if (ownerPending?.fileName) return ownerPending\n\n const ownerMemo = owner?.memoizedProps?.__source\n if (ownerMemo?.fileName) return ownerMemo\n\n const pending = fiber?.pendingProps?.__source\n if (pending?.fileName) return pending\n\n const memo = fiber?.memoizedProps?.__source\n if (memo?.fileName) return memo\n\n const fromDebugStack = getSourceFromDebugStack(fiber)\n if (fromDebugStack?.fileName) return fromDebugStack\n\n return null\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction buildFrame(fiber: any): ReactComponentFrame | null {\n const type = fiber?.type\n if (typeof type !== 'function' && typeof type !== 'object') return null\n\n const name = type?.displayName || type?.name || null\n if (!name || name === 'Fragment') return null\n\n const frame: ReactComponentFrame = { name }\n const source = getSourceFromFiber(fiber)\n if (source?.fileName) {\n frame.file = source.fileName\n if (typeof source.lineNumber === 'number') {\n frame.line = source.lineNumber\n }\n if (typeof source.columnNumber === 'number') {\n frame.column = source.columnNumber\n }\n }\n\n return frame\n}\n\nfunction shouldIncludeFrame(\n frame: ReactComponentFrame,\n lastFrame: ReactComponentFrame | null\n): boolean {\n if (!lastFrame) return true\n if (frame.name !== lastFrame.name) return true\n if (!lastFrame.file && frame.file) return true\n if (lastFrame.file && frame.file && lastFrame.line == null && frame.line != null) return true\n if (\n lastFrame.file &&\n frame.file &&\n lastFrame.line != null &&\n frame.line != null &&\n lastFrame.column == null &&\n frame.column != null\n ) {\n return true\n }\n return false\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getOwnerStack(fiber: any): ReactComponentFrame[] {\n const frames: ReactComponentFrame[] = []\n let current = fiber\n let lastFrame: ReactComponentFrame | null = null\n\n while (current) {\n const frame = buildFrame(current)\n if (frame && shouldIncludeFrame(frame, lastFrame)) {\n frames.push(frame)\n lastFrame = frame\n }\n current = current._debugOwner\n }\n\n return frames\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getRenderStack(fiber: any): ReactComponentFrame[] {\n const frames: ReactComponentFrame[] = []\n let current = fiber\n let lastFrame: ReactComponentFrame | null = null\n\n while (current) {\n const frame = buildFrame(current)\n if (frame && shouldIncludeFrame(frame, lastFrame)) {\n frames.push(frame)\n lastFrame = frame\n }\n current = current.return\n }\n\n return frames\n}\n\nfunction getReactComponentStack(element: HTMLElement): ReactComponentFrame[] {\n const fiber = getFiberForElement(element)\n if (!fiber) return []\n\n const ownerStack = getOwnerStack(fiber)\n if (ownerStack.length > 0) {\n return ownerStack\n }\n\n return getRenderStack(fiber)\n}\n\ninterface ChildBriefInfo {\n name: string\n textPreview: string\n source: DomSourceLocation | null\n}\n\nexport function getElementDisplayName(element: HTMLElement): string {\n const tag = element.tagName.toLowerCase()\n if (element.id) return `${tag}#${element.id}`\n const firstClass = Array.from(element.classList)\n .find(c => c && !c.startsWith('direct-edit'))\n if (firstClass) return `${tag}.${firstClass}`\n return tag\n}\n\n/** Lightweight info for a child element, used in reorder data. Does NOT call getElementLocator. */\nexport function getChildBriefInfo(element: HTMLElement): ChildBriefInfo {\n const name = getElementDisplayName(element)\n const raw = ((element.innerText || element.textContent) ?? '').replace(/\\s+/g, ' ').trim()\n const textPreview = raw.length > 40 ? `${raw.slice(0, 37)}...` : raw\n const source = getElementSource(element)\n return { name, textPreview, source }\n}\n\nconst STABLE_ATTRIBUTES = ['data-testid', 'data-qa', 'data-cy', 'aria-label', 'role'] as const\nconst MAX_SELECTOR_DEPTH = 24\nconst CONTEXT_ALLOWED_ATTRIBUTES = new Set([\n 'id',\n 'class',\n 'href',\n 'src',\n 'alt',\n 'aria-label',\n 'role',\n 'data-testid',\n 'data-qa',\n 'data-cy',\n 'data-direct-edit-target',\n])\n\nfunction escapeCssIdentifier(value: string): string {\n if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {\n return CSS.escape(value)\n }\n return value.replace(/[^a-zA-Z0-9_-]/g, (char) => `\\\\${char}`)\n}\n\nfunction escapeAttributeValue(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')\n}\n\nfunction isUniqueSelector(selector: string): boolean {\n if (typeof document === 'undefined') return false\n try {\n return document.querySelectorAll(selector).length === 1\n } catch {\n return false\n }\n}\n\nfunction getUniqueIdSelector(element: HTMLElement): string | null {\n if (!element.id) return null\n const selector = `#${escapeCssIdentifier(element.id)}`\n return isUniqueSelector(selector) ? selector : null\n}\n\nfunction getStableAttributeSelector(element: HTMLElement): string | null {\n const tagName = element.tagName.toLowerCase()\n for (const attr of STABLE_ATTRIBUTES) {\n const value = element.getAttribute(attr)\n if (!value) continue\n const selector = `${tagName}[${attr}=\"${escapeAttributeValue(value)}\"]`\n if (isUniqueSelector(selector)) {\n return selector\n }\n }\n return null\n}\n\nfunction getNthOfTypeSelector(element: HTMLElement): string {\n const tagName = element.tagName.toLowerCase()\n const classes = Array.from(element.classList)\n .filter((className) => className && !className.startsWith('direct-edit'))\n .slice(0, 2)\n const classSelector = classes.map((className) => `.${escapeCssIdentifier(className)}`).join('')\n\n let nthOfType = ''\n const parent = element.parentElement\n if (parent) {\n const siblings = Array.from(parent.children).filter(\n (child) => (child as HTMLElement).tagName.toLowerCase() === tagName\n )\n if (siblings.length > 1) {\n const index = siblings.indexOf(element) + 1\n nthOfType = `:nth-of-type(${index})`\n }\n }\n\n return `${tagName}${classSelector}${nthOfType}`\n}\n\nfunction buildDomSelector(element: HTMLElement): string {\n if (typeof document === 'undefined') {\n return element.tagName.toLowerCase()\n }\n if (element.closest('[data-direct-edit]')) return ''\n\n const uniqueId = getUniqueIdSelector(element)\n if (uniqueId) return uniqueId\n\n const stableAttribute = getStableAttributeSelector(element)\n if (stableAttribute) return stableAttribute\n\n const segments: string[] = []\n let current: HTMLElement | null = element\n let depth = 0\n\n while (current && current !== document.body && depth < MAX_SELECTOR_DEPTH) {\n if (current.hasAttribute('data-direct-edit')) {\n current = current.parentElement\n continue\n }\n\n if (depth > 0) {\n const parentId = getUniqueIdSelector(current)\n if (parentId) {\n segments.unshift(parentId)\n break\n }\n const parentStableAttr = getStableAttributeSelector(current)\n if (parentStableAttr) {\n segments.unshift(parentStableAttr)\n break\n }\n }\n\n segments.unshift(getNthOfTypeSelector(current))\n current = current.parentElement\n depth += 1\n }\n\n return segments.join(' > ')\n}\n\nfunction stripDirectEditNodes(root: Element) {\n const nodes = root.querySelectorAll('[data-direct-edit]')\n nodes.forEach((node) => node.remove())\n}\n\nfunction sanitizeContextNode(root: HTMLElement) {\n const nodes: HTMLElement[] = [root, ...Array.from(root.querySelectorAll<HTMLElement>('*'))]\n for (const node of nodes) {\n for (const attr of Array.from(node.attributes)) {\n if (!CONTEXT_ALLOWED_ATTRIBUTES.has(attr.name)) {\n node.removeAttribute(attr.name)\n }\n }\n }\n}\n\nfunction buildTargetHtml(element: HTMLElement): string {\n const tagName = element.tagName.toLowerCase()\n const attrs: string[] = []\n const allowList = [\n 'id',\n 'class',\n 'href',\n 'src',\n 'alt',\n 'aria-label',\n 'role',\n 'data-testid',\n ]\n const maxAttrLength = 48\n\n for (const attr of allowList) {\n const value = element.getAttribute(attr)\n if (!value) continue\n const trimmed = value.length > maxAttrLength ? `${value.slice(0, maxAttrLength - 3)}...` : value\n attrs.push(`${attr}=\"${escapeAttributeValue(trimmed)}\"`)\n }\n\n const text = getTextPreview(element)\n const attrString = attrs.length > 0 ? ` ${attrs.join(' ')}` : ''\n\n if (text) {\n return `<${tagName}${attrString}>\\n ${escapeHtml(text)}\\n</${tagName}>`\n }\n\n return `<${tagName}${attrString}></${tagName}>`\n}\n\nfunction formatSourcePath(file: string): string {\n const normalized = file\n .replace(/\\\\/g, '/')\n .replace(/^webpack:\\/\\/\\//, '')\n .replace(/^webpack:\\/\\//, '')\n .replace(/^webpack-internal:\\/\\//, '')\n .replace(/^rsc:\\/\\/React\\/Server\\//, '')\n .replace(/^about:\\/\\/React\\//, '')\n .replace(/^file:\\/\\//, '')\n .replace(/^\\/\\(app-pages-browser\\)\\//, '/')\n .replace(/^\\/app-pages-browser\\//, '/')\n .replace(/^_N_E\\//, '')\n .replace(/^\\.\\/+/, '')\n const packagesIndex = normalized.indexOf('/packages/')\n if (packagesIndex !== -1) {\n return `/[project]${normalized.slice(packagesIndex)}`\n }\n const appIndex = normalized.indexOf('/app/')\n if (appIndex !== -1) {\n return `/[project]${normalized.slice(appIndex)}`\n }\n const srcIndex = normalized.indexOf('/src/')\n if (srcIndex !== -1) {\n return `/[project]${normalized.slice(srcIndex)}`\n }\n return normalized\n}\n\nfunction formatSourceLocation(file: string, line?: number, column?: number): string {\n const formatted = formatSourcePath(file)\n if (typeof line === 'number') {\n const columnSuffix = typeof column === 'number' ? `:${column}` : ''\n return `${formatted}:${line}${columnSuffix}`\n }\n return formatted\n}\n\nfunction isUserlandSource(file: string): boolean {\n const normalized = file.replace(/\\\\/g, '/')\n if (\n normalized.includes('node_modules') ||\n normalized.includes('next/dist') ||\n normalized.includes('react') ||\n normalized.includes('react-dom') ||\n normalized.includes('direct-edit')\n ) {\n return false\n }\n return (\n normalized.includes('/app/') ||\n normalized.includes('/src/') ||\n normalized.includes('/packages/') ||\n normalized.startsWith('./')\n )\n}\n\nfunction getPrimaryFrame(locator: ElementLocator): ReactComponentFrame | null {\n for (const frame of locator.reactStack) {\n if (frame.file && isUserlandSource(frame.file)) {\n return frame\n }\n }\n for (const frame of locator.reactStack) {\n if (frame.file) {\n return frame\n }\n }\n return locator.reactStack[0] ?? null\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n}\n\nfunction buildDomContextHtml(\n element: HTMLElement,\n options?: { siblingCount?: number }\n): string {\n const parent = element.parentElement\n if (!parent) {\n const clone = element.cloneNode(true) as HTMLElement\n clone.setAttribute('data-direct-edit-target', 'true')\n stripDirectEditNodes(clone)\n sanitizeContextNode(clone)\n return clone.outerHTML\n }\n\n const parentClone = parent.cloneNode(false) as HTMLElement\n const siblings = Array.from(parent.children) as HTMLElement[]\n const selectedIndex = siblings.indexOf(element)\n const siblingCount = options?.siblingCount ?? 1\n let slice = siblings\n\n if (siblingCount >= 0 && selectedIndex >= 0) {\n const start = Math.max(0, selectedIndex - siblingCount)\n const end = Math.min(siblings.length, selectedIndex + siblingCount + 1)\n slice = siblings.slice(start, end)\n }\n\n for (const sibling of slice) {\n if (sibling.closest('[data-direct-edit]')) continue\n const clone = sibling.cloneNode(true) as HTMLElement\n if (sibling === element) {\n clone.setAttribute('data-direct-edit-target', 'true')\n }\n stripDirectEditNodes(clone)\n sanitizeContextNode(clone)\n parentClone.appendChild(clone)\n }\n\n sanitizeContextNode(parentClone)\n return parentClone.outerHTML\n}\n\nfunction normalizePreviewWhitespace(value: string): string {\n return value.replace(/\\s+/g, ' ').trim()\n}\n\nfunction isWordLikeChar(char: string): boolean {\n return /[A-Za-z0-9]/.test(char)\n}\n\nfunction getFallbackTextPreview(element: HTMLElement): string {\n const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT)\n const tokens: string[] = []\n let previousRaw = ''\n let previousParent: HTMLElement | null = null\n\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n const textNode = node as Text\n const raw = textNode.textContent ?? ''\n const normalized = normalizePreviewWhitespace(raw)\n if (!normalized) continue\n\n if (tokens.length > 0) {\n const hasExplicitWhitespace = /^\\s/.test(raw) || /\\s$/.test(previousRaw)\n const prevLast = previousRaw.slice(-1)\n const nextFirst = normalized[0]\n const shouldInsertHeuristicSpace =\n previousParent !== textNode.parentElement &&\n isWordLikeChar(prevLast) &&\n isWordLikeChar(nextFirst)\n\n if (hasExplicitWhitespace || shouldInsertHeuristicSpace) {\n tokens.push(' ')\n }\n }\n\n tokens.push(normalized)\n previousRaw = raw\n previousParent = textNode.parentElement\n }\n\n return tokens.join('')\n}\n\nfunction getTextPreview(element: HTMLElement): string {\n const innerTextCandidate = normalizePreviewWhitespace(element.innerText ?? '')\n const text = innerTextCandidate || getFallbackTextPreview(element)\n if (text.length <= 120) {\n return text\n }\n return `${text.slice(0, 117)}...`\n}\n\nfunction parseDomSource(element: HTMLElement): DomSourceLocation | null {\n const value = element.getAttribute('data-direct-edit-source')\n if (!value) return null\n\n let file = value\n let line: number | undefined\n let column: number | undefined\n\n const lastColon = value.lastIndexOf(':')\n if (lastColon !== -1) {\n const maybeColumn = Number(value.slice(lastColon + 1))\n if (!Number.isNaN(maybeColumn)) {\n column = maybeColumn\n file = value.slice(0, lastColon)\n\n const prevColon = file.lastIndexOf(':')\n if (prevColon !== -1) {\n const maybeLine = Number(file.slice(prevColon + 1))\n if (!Number.isNaN(maybeLine)) {\n line = maybeLine\n file = file.slice(0, prevColon)\n }\n }\n }\n }\n\n return { file, line, column }\n}\n\n/** Resolve the source location for an element: data-direct-edit-source attribute, then fiber fallback. */\nexport function getElementSource(element: HTMLElement): DomSourceLocation | null {\n const domSource = parseDomSource(element)\n if (domSource) return domSource\n\n // Fallback: get source from the element's own React fiber when\n // the Vite plugin attribute is not present\n const seenFibers = new Set<any>()\n let fiber = getFiberForElement(element)\n while (fiber && !seenFibers.has(fiber)) {\n seenFibers.add(fiber)\n const fiberSource = getSourceFromFiber(fiber)\n if (fiberSource?.fileName) {\n return {\n file: fiberSource.fileName,\n line: fiberSource.lineNumber,\n column: fiberSource.columnNumber,\n }\n }\n fiber = fiber._debugOwner ?? fiber.return ?? null\n }\n return null\n}\n\nexport function getElementLocator(element: HTMLElement): ElementLocator {\n const elementInfo = getElementInfo(element)\n const domSource = getElementSource(element)\n\n return {\n reactStack: getReactComponentStack(element),\n domSelector: buildDomSelector(element),\n domContextHtml: buildDomContextHtml(element),\n targetHtml: buildTargetHtml(element),\n textPreview: getTextPreview(element),\n tagName: elementInfo.tagName,\n id: elementInfo.id,\n classList: elementInfo.classList,\n domSource: domSource ?? undefined,\n }\n}\n\ninterface ExportChange {\n property: string\n value: string\n tailwind: string\n}\n\nfunction getLocatorHeader(locator: ElementLocator): { componentLabel: string; formattedSource: string | null } {\n const primaryFrame = getPrimaryFrame(locator)\n const componentLabel = primaryFrame?.name ? primaryFrame.name : locator.tagName\n const formattedSource = locator.domSource?.file\n ? formatSourceLocation(locator.domSource.file, locator.domSource.line, locator.domSource.column)\n : primaryFrame?.file\n ? formatSourceLocation(primaryFrame.file, primaryFrame.line, primaryFrame.column)\n : null\n return { componentLabel, formattedSource }\n}\n\nfunction buildLocatorContextLines(locator: ElementLocator, options?: { skipContext?: boolean }): string[] {\n const lines: string[] = []\n const { componentLabel, formattedSource } = getLocatorHeader(locator)\n const target = (locator.targetHtml || locator.domContextHtml || '').trim()\n const context = locator.domContextHtml?.trim() || ''\n const selector = locator.domSelector?.trim()\n const text = locator.textPreview?.trim()\n\n lines.push(`@<${componentLabel}>`)\n lines.push('')\n if (target) {\n lines.push('target:')\n lines.push(target)\n }\n if (!options?.skipContext && context && context !== target) {\n lines.push('context:')\n lines.push(context)\n }\n lines.push(`in ${formattedSource ?? '(file not available)'}`)\n if (selector) {\n lines.push(`selector: ${selector}`)\n }\n if (text) {\n lines.push(`text: ${text}`)\n }\n\n return lines\n}\n\nexport function buildElementContext(locator: ElementLocator): string {\n return buildLocatorContextLines(locator).join('\\n')\n}\n\n/** Whether a session edit has any meaningful changes (styles, text, or move). */\nexport function hasSessionEditChanges(edit: SessionEdit): boolean {\n return Object.keys(edit.pendingStyles).length > 0 || Boolean(edit.textEdit) || Boolean(edit.move)\n}\n\n/**\n * Partition multi-selected elements into edits with changes vs context-only blocks.\n * Returns the edits that have meaningful changes and context markdown for the rest.\n */\nexport function partitionMultiSelectedEdits(\n elements: HTMLElement[],\n sessionEditsRef: { current: Map<HTMLElement, SessionEdit> },\n): { editsWithChanges: SessionEdit[]; contextBlocks: string[] } {\n const editsWithChanges: SessionEdit[] = []\n const contextBlocks: string[] = []\n for (const el of elements) {\n if (!el.isConnected) continue\n const edit = sessionEditsRef.current.get(el)\n if (edit && hasSessionEditChanges(edit)) {\n editsWithChanges.push(edit)\n } else {\n contextBlocks.push(buildElementContext(getElementLocator(el)))\n }\n }\n return { editsWithChanges, contextBlocks }\n}\n\n/**\n * Collect context blocks for multi-selected elements not already in a session items list.\n */\nexport function getContextOnlyBlocks(\n selectedElements: HTMLElement[],\n sessionItems: SessionItem[],\n): string[] {\n if (selectedElements.length <= 1) return []\n const sessionElementSet = new Set(\n sessionItems.filter((i) => i.type === 'edit').map((i) => i.edit.element),\n )\n const blocks: string[] = []\n for (const el of selectedElements) {\n if (!el.isConnected || sessionElementSet.has(el)) continue\n blocks.push(buildElementContext(getElementLocator(el)))\n }\n return blocks\n}\n\nconst spacingGroups = [\n { top: 'padding-top', right: 'padding-right', bottom: 'padding-bottom', left: 'padding-left', all: 'padding', inline: 'padding-inline', block: 'padding-block' },\n { top: 'margin-top', right: 'margin-right', bottom: 'margin-bottom', left: 'margin-left', all: 'margin', inline: 'margin-inline', block: 'margin-block' },\n] as const\n\nexport function collapseSpacingShorthands(styles: Record<string, string>): Record<string, string> {\n const result = { ...styles }\n\n for (const group of spacingGroups) {\n const hasTop = group.top in result\n const hasRight = group.right in result\n const hasBottom = group.bottom in result\n const hasLeft = group.left in result\n const hasAllSides = hasTop && hasRight && hasBottom && hasLeft\n\n if (hasAllSides) {\n delete result[group.all]\n delete result[group.inline]\n delete result[group.block]\n }\n\n const top = result[group.top]\n const right = result[group.right]\n const bottom = result[group.bottom]\n const left = result[group.left]\n\n const horizontalMatch = hasLeft && hasRight && left === right\n const verticalMatch = hasTop && hasBottom && top === bottom\n\n if (horizontalMatch && verticalMatch) {\n delete result[group.top]\n delete result[group.right]\n delete result[group.bottom]\n delete result[group.left]\n if (top === left) {\n result[group.all] = top\n } else {\n result[group.inline] = left\n result[group.block] = top\n }\n } else if (horizontalMatch) {\n // Only horizontal pair matches\n delete result[group.left]\n delete result[group.right]\n result[group.inline] = left\n } else if (verticalMatch) {\n // Only vertical pair matches\n delete result[group.top]\n delete result[group.bottom]\n result[group.block] = top\n }\n }\n\n return result\n}\n\nfunction collapseFourSideShorthand(\n result: Record<string, string>,\n sides: { top: string; right: string; bottom: string; left: string; all: string }\n): void {\n if (!(sides.top in result && sides.right in result && sides.bottom in result && sides.left in result)) return\n\n // Side-specific values are the source of truth when all four are present.\n delete result[sides.all]\n\n const top = result[sides.top]\n const right = result[sides.right]\n const bottom = result[sides.bottom]\n const left = result[sides.left]\n const allEqual = top === right && top === bottom && top === left\n if (!allEqual) return\n\n delete result[sides.top]\n delete result[sides.right]\n delete result[sides.bottom]\n delete result[sides.left]\n result[sides.all] = top\n}\n\nexport function collapseExportShorthands(styles: Record<string, string>): Record<string, string> {\n const result = collapseSpacingShorthands(styles)\n\n collapseFourSideShorthand(result, {\n top: 'border-top-style',\n right: 'border-right-style',\n bottom: 'border-bottom-style',\n left: 'border-left-style',\n all: 'border-style',\n })\n\n collapseFourSideShorthand(result, {\n top: 'border-top-width',\n right: 'border-right-width',\n bottom: 'border-bottom-width',\n left: 'border-left-width',\n all: 'border-width',\n })\n\n collapseFourSideShorthand(result, {\n top: 'border-top-left-radius',\n right: 'border-top-right-radius',\n bottom: 'border-bottom-right-radius',\n left: 'border-bottom-left-radius',\n all: 'border-radius',\n })\n\n return result\n}\n\nexport function buildEditExport(\n locator: ElementLocator,\n pendingStyles: Record<string, string>,\n textEdit?: { originalText: string; newText: string } | null\n): string\nexport function buildEditExport(\n element: HTMLElement | null,\n elementInfo: ElementInfo,\n computedSpacing: SpacingProperties | null,\n computedBorderRadius: BorderRadiusProperties | null,\n computedFlex: FlexProperties | null,\n computedSizing: SizingProperties | null,\n pendingStyles: Record<string, string>\n): string\nexport function buildEditExport(\n arg1: ElementLocator | HTMLElement | null,\n arg2: ElementInfo | Record<string, string>,\n arg3?: SpacingProperties | null | { originalText: string; newText: string },\n arg4?: BorderRadiusProperties | null,\n arg5?: FlexProperties | null,\n arg6?: SizingProperties | null,\n arg7?: Record<string, string>\n): string {\n const isLocator = Boolean(arg1 && typeof arg1 === 'object' && 'domSelector' in arg1)\n if (!isLocator) {\n void arg4\n void arg5\n void arg6\n }\n const pendingStyles = (isLocator ? (arg2 as Record<string, string>) : arg7) || {}\n const textEdit = isLocator && arg3 && typeof arg3 === 'object' && 'originalText' in arg3\n ? (arg3 as { originalText: string; newText: string })\n : null\n let locator: ElementLocator\n\n if (isLocator) {\n locator = arg1 as ElementLocator\n } else {\n const element = arg1 as HTMLElement | null\n const elementInfo = arg2 as ElementInfo\n locator = element\n ? getElementLocator(element)\n : {\n reactStack: [],\n domSelector: elementInfo.id ? `#${elementInfo.id}` : elementInfo.tagName,\n domContextHtml: `<${elementInfo.tagName}${elementInfo.id ? ` id=\"${elementInfo.id}\"` : ''} data-direct-edit-target=\"true\"></${elementInfo.tagName}>`,\n targetHtml: `<${elementInfo.tagName}${elementInfo.id ? ` id=\"${elementInfo.id}\"` : ''}></${elementInfo.tagName}>`,\n textPreview: '',\n tagName: elementInfo.tagName,\n id: elementInfo.id,\n classList: elementInfo.classList,\n }\n }\n\n const changes: ExportChange[] = []\n\n const collapsedStyles = collapseExportShorthands(pendingStyles)\n for (const [property, value] of Object.entries(collapsedStyles)) {\n const tailwindClass = stylesToTailwind({ [property]: value })\n changes.push({\n property,\n value,\n tailwind: tailwindClass,\n })\n }\n\n const lines = buildLocatorContextLines(locator)\n lines.push('')\n if (changes.length > 0) {\n lines.push('edits:')\n for (const change of changes) {\n const tailwind = change.tailwind ? ` (${change.tailwind})` : ''\n lines.push(`${change.property}: ${change.value}${tailwind}`)\n }\n }\n\n if (textEdit) {\n lines.push('text content changed:')\n lines.push(`from: \"${textEdit.originalText}\"`)\n lines.push(`to: \"${textEdit.newText}\"`)\n }\n\n return lines.join('\\n')\n}\n\n/** Like buildEditExport but with options to skip context HTML (for move edits). */\nfunction buildEditExportWithOptions(\n locator: ElementLocator,\n pendingStyles: Record<string, string>,\n textEdit?: { originalText: string; newText: string } | null,\n options?: { skipContext?: boolean }\n): string {\n const changes: ExportChange[] = []\n const collapsedStyles = collapseExportShorthands(pendingStyles)\n for (const [property, value] of Object.entries(collapsedStyles)) {\n const tailwindClass = stylesToTailwind({ [property]: value })\n changes.push({ property, value, tailwind: tailwindClass })\n }\n\n const lines = buildLocatorContextLines(locator, options)\n lines.push('')\n if (changes.length > 0) {\n lines.push('edits:')\n for (const change of changes) {\n const tailwind = change.tailwind ? ` (${change.tailwind})` : ''\n lines.push(`${change.property}: ${change.value}${tailwind}`)\n }\n }\n\n if (textEdit) {\n lines.push('text content changed:')\n lines.push(`from: \"${textEdit.originalText}\"`)\n lines.push(`to: \"${textEdit.newText}\"`)\n }\n\n return lines.join('\\n')\n}\n\nexport function buildCommentExport(\n locator: ElementLocator,\n commentText: string,\n replies?: Array<{ text: string; createdAt: number }>\n): string {\n const lines = buildLocatorContextLines(locator)\n lines.push('')\n lines.push(`comment: ${commentText}`)\n if (replies && replies.length > 0) {\n for (const reply of replies) {\n lines.push(`reply: ${reply.text}`)\n }\n }\n\n return lines.join('\\n')\n}\n\nfunction normalizeSelector(selector: string | null | undefined): string | null {\n const value = selector?.trim()\n return value && value.length > 0 ? value : null\n}\n\nfunction normalizeName(name: string | null | undefined): string {\n return name?.trim().toLowerCase() || 'element'\n}\n\nfunction buildAnchorRef(\n name: string | null | undefined,\n selector: string | null | undefined,\n source: DomSourceLocation | null | undefined\n): AnchorRef {\n return {\n name: name?.trim() || 'element',\n selector: normalizeSelector(selector),\n source: source?.file ? source : null,\n }\n}\n\nfunction anchorKey(anchor: AnchorRef | null | undefined): string {\n if (!anchor) return 'none'\n const selector = normalizeSelector(anchor.selector)\n if (selector) return `selector:${selector}`\n if (anchor.source?.file) {\n return `source:${anchor.source.file}:${anchor.source.line ?? 0}:${anchor.source.column ?? 0}`\n }\n return `name:${normalizeName(anchor.name)}`\n}\n\nfunction anchorsEqual(a: AnchorRef | null | undefined, b: AnchorRef | null | undefined): boolean {\n if (!a && !b) return true\n if (!a || !b) return false\n const aSelector = normalizeSelector(a.selector)\n const bSelector = normalizeSelector(b.selector)\n if (aSelector && bSelector) return aSelector === bSelector\n if (a.source?.file && b.source?.file) {\n return (\n a.source.file === b.source.file\n && (a.source.line ?? null) === (b.source.line ?? null)\n && (a.source.column ?? null) === (b.source.column ?? null)\n )\n }\n return normalizeName(a.name) === normalizeName(b.name)\n}\n\nfunction formatAnchorRef(anchor: AnchorRef | null | undefined, fallback = '(none)'): string {\n if (!anchor) return fallback\n const selector = normalizeSelector(anchor.selector)\n if (selector) return selector\n if (anchor.source?.file) return `<${anchor.name}> @ ${formatSourceLocation(anchor.source.file, anchor.source.line, anchor.source.column)}`\n return `<${anchor.name}>`\n}\n\nfunction buildPlacementRef(before: AnchorRef | null, after: AnchorRef | null): PlacementRef {\n if (before && after) {\n return {\n before,\n after,\n description: `between after ${formatAnchorRef(before)} and before ${formatAnchorRef(after)}`,\n }\n }\n if (before) {\n return {\n before,\n after: null,\n description: `after ${formatAnchorRef(before)}`,\n }\n }\n if (after) {\n return {\n before: null,\n after,\n description: `before ${formatAnchorRef(after)}`,\n }\n }\n return {\n before: null,\n after: null,\n description: 'as the only child',\n }\n}\n\nfunction buildPlacementFromMove(\n beforeName: string | null | undefined,\n beforeSelector: string | null | undefined,\n beforeSource: DomSourceLocation | null | undefined,\n afterName: string | null | undefined,\n afterSelector: string | null | undefined,\n afterSource: DomSourceLocation | null | undefined\n): PlacementRef {\n const before = (beforeName || beforeSelector || beforeSource?.file)\n ? buildAnchorRef(beforeName, beforeSelector, beforeSource)\n : null\n const after = (afterName || afterSelector || afterSource?.file)\n ? buildAnchorRef(afterName, afterSelector, afterSource)\n : null\n return buildPlacementRef(before, after)\n}\n\nfunction toRoundedVisualDelta(move: NonNullable<SessionEdit['move']>): { x: number; y: number } | undefined {\n const delta = move.visualDelta ?? move.positionDelta\n if (!delta) return undefined\n const rounded = { x: Math.round(delta.x), y: Math.round(delta.y) }\n return rounded.x === 0 && rounded.y === 0 ? undefined : rounded\n}\n\nfunction hasVisualIntent(move: NonNullable<SessionEdit['move']>): boolean {\n return Boolean(toRoundedVisualDelta(move))\n}\n\nfunction hasStructuralChange(move: NonNullable<SessionEdit['move']>): boolean {\n const fromParent = buildAnchorRef(move.fromParentName, move.fromParentSelector, move.fromParentSource)\n const toParent = buildAnchorRef(move.toParentName, move.toParentSelector, move.toParentSource)\n const fromPlacement = buildPlacementFromMove(\n move.fromSiblingBefore,\n move.fromSiblingBeforeSelector,\n move.fromSiblingBeforeSource,\n move.fromSiblingAfter,\n move.fromSiblingAfterSelector,\n move.fromSiblingAfterSource,\n )\n const toPlacement = buildPlacementFromMove(\n move.toSiblingBefore,\n move.toSiblingBeforeSelector,\n move.toSiblingBeforeSource,\n move.toSiblingAfter,\n move.toSiblingAfterSelector,\n move.toSiblingAfterSource,\n )\n\n if (!anchorsEqual(fromParent, toParent)) return true\n if (!anchorsEqual(fromPlacement.before, toPlacement.before)) return true\n if (!anchorsEqual(fromPlacement.after, toPlacement.after)) return true\n if (typeof move.fromIndex === 'number' && typeof move.toIndex === 'number' && move.fromIndex !== move.toIndex) return true\n return false\n}\n\nfunction isStructuredLayoutContainer(layout: NonNullable<SessionEdit['move']>['fromParentLayout'] | undefined): boolean {\n return layout === 'flex' || layout === 'grid'\n}\n\nfunction isExistingFlexWorkflow(move: NonNullable<SessionEdit['move']>): boolean {\n const structuralChange = hasStructuralChange(move)\n if (!structuralChange) return false\n\n const fromParent = buildAnchorRef(move.fromParentName, move.fromParentSelector, move.fromParentSource)\n const toParent = buildAnchorRef(move.toParentName, move.toParentSelector, move.toParentSource)\n const sameParent = anchorsEqual(fromParent, toParent)\n const fromLayout = move.fromParentLayout\n const toLayout = move.toParentLayout\n\n if (sameParent) {\n return Boolean(move.mode === 'reorder' && (isStructuredLayoutContainer(toLayout) || isStructuredLayoutContainer(fromLayout)))\n }\n return Boolean(isStructuredLayoutContainer(fromLayout) && isStructuredLayoutContainer(toLayout))\n}\n\nfunction classifyMove(move: NonNullable<SessionEdit['move']>): MoveClassification | 'noop' {\n const structuralChange = hasStructuralChange(move)\n const visualIntent = hasVisualIntent(move)\n if (!structuralChange && !visualIntent) return 'noop'\n if (isExistingFlexWorkflow(move)) return 'existing_layout_move'\n if (move.mode === 'free' || move.mode === 'position') return 'layout_refactor'\n if (!structuralChange && visualIntent) return 'layout_refactor'\n return 'layout_refactor'\n}\n\ninterface NumericCluster {\n center: number\n values: number[]\n}\n\nfunction buildNumericClusters(values: number[], tolerance: number): NumericCluster[] {\n if (values.length === 0) return []\n const sorted = [...values].sort((a, b) => a - b)\n const clusters: NumericCluster[] = [{ center: sorted[0], values: [sorted[0]] }]\n for (let i = 1; i < sorted.length; i++) {\n const value = sorted[i]\n const current = clusters[clusters.length - 1]\n if (Math.abs(value - current.center) <= tolerance) {\n current.values.push(value)\n current.center = current.values.reduce((sum, n) => sum + n, 0) / current.values.length\n } else {\n clusters.push({ center: value, values: [value] })\n }\n }\n return clusters\n}\n\nfunction inferFlexDirection(\n sameRowCount: number,\n sameColumnCount: number,\n visualDelta?: { x: number; y: number }\n): { direction: 'row' | 'column'; reason: string } {\n if (sameRowCount > sameColumnCount) {\n return { direction: 'row', reason: 'Subject aligns with neighboring anchors on the same row.' }\n }\n if (sameColumnCount > sameRowCount) {\n return { direction: 'column', reason: 'Subject aligns with neighboring anchors on the same column.' }\n }\n if (sameRowCount > 0) {\n return { direction: 'row', reason: 'Detected row alignment in final geometry.' }\n }\n if (sameColumnCount > 0) {\n return { direction: 'column', reason: 'Detected column alignment in final geometry.' }\n }\n const horizontalDominant = Math.abs(visualDelta?.x ?? 0) >= Math.abs(visualDelta?.y ?? 0)\n return {\n direction: horizontalDominant ? 'row' : 'column',\n reason: 'Fell back to movement axis because anchor alignment was ambiguous.',\n }\n}\n\nfunction inferLayoutPrescription(\n edit: SessionEdit,\n operation: Omit<MoveOperation, 'operationId'>,\n reasons: string[]\n): LayoutPrescription {\n const parent = edit.element.parentElement\n if (!parent || !edit.element.isConnected) {\n return {\n recommendedSystem: 'flex',\n intentPatterns: ['no_geometry_context'],\n refactorSteps: [\n `Reparent ${formatAnchorRef(operation.subject)} under ${formatAnchorRef(operation.to.parent)} at ${operation.to.placement.description}.`,\n ],\n styleSteps: [\n `Convert ${formatAnchorRef(operation.to.parent)} to flex and set a clear primary axis for this relationship.`,\n 'Use `gap` for spacing and keep positioning static.',\n ],\n itemSteps: [\n 'Remove any inline `left/top/transform` move artifacts from moved elements.',\n ],\n }\n }\n\n const children = Array.from(parent.children).filter(\n (node) => node instanceof HTMLElement && isInFlowChild(node) && !node.hasAttribute('data-direct-edit')\n ) as HTMLElement[]\n const childSnapshots = children.map((child) => {\n const rect = child.getBoundingClientRect()\n const locator = getElementLocator(child)\n const anchor = buildAnchorRef(getElementDisplayName(child), locator.domSelector, locator.domSource)\n return {\n child,\n rect,\n centerX: rect.left + rect.width / 2,\n centerY: rect.top + rect.height / 2,\n anchor,\n anchorLabel: formatAnchorRef(anchor),\n }\n })\n const subjectSnapshot = childSnapshots.find((snapshot) => snapshot.child === edit.element)\n const subjectRect = edit.element.getBoundingClientRect()\n const subjectCenterX = subjectRect.left + subjectRect.width / 2\n const subjectCenterY = subjectRect.top + subjectRect.height / 2\n const rowTolerance = Math.max(8, subjectRect.height * 0.35)\n const colTolerance = Math.max(8, subjectRect.width * 0.35)\n\n const sameRowWith: string[] = []\n const sameColumnWith: string[] = []\n const sameRowNodes: typeof childSnapshots = []\n let aboveAnchor: string | null = null\n let belowAnchor: string | null = null\n let bestAboveDistance = Number.POSITIVE_INFINITY\n let bestBelowDistance = Number.POSITIVE_INFINITY\n\n for (const node of childSnapshots) {\n if (node.child === edit.element) continue\n\n if (Math.abs(node.centerY - subjectCenterY) <= rowTolerance) {\n sameRowWith.push(node.anchorLabel)\n sameRowNodes.push(node)\n }\n if (Math.abs(node.centerX - subjectCenterX) <= colTolerance) {\n sameColumnWith.push(node.anchorLabel)\n }\n\n const yDelta = node.centerY - subjectCenterY\n if (yDelta < 0 && Math.abs(yDelta) < bestAboveDistance) {\n bestAboveDistance = Math.abs(yDelta)\n aboveAnchor = node.anchorLabel\n }\n if (yDelta > 0 && yDelta < bestBelowDistance) {\n bestBelowDistance = yDelta\n belowAnchor = node.anchorLabel\n }\n }\n\n const rowCenters = childSnapshots.map(({ centerY }) => centerY)\n const colCenters = childSnapshots.map(({ centerX }) => centerX)\n const rowClusters = buildNumericClusters(rowCenters, rowTolerance)\n const colClusters = buildNumericClusters(colCenters, colTolerance)\n const denseRowClusters = rowClusters.filter(cluster => cluster.values.length >= 2).length\n const denseColClusters = colClusters.filter(cluster => cluster.values.length >= 2).length\n const isTwoDimensional = childSnapshots.length >= 4 && denseRowClusters >= 2 && denseColClusters >= 2\n const recommendedSystem: 'flex' | 'grid' = isTwoDimensional ? 'grid' : 'flex'\n\n const intentPatterns: string[] = []\n if (sameRowWith.length > 0) intentPatterns.push(`same_row_with:${sameRowWith.slice(0, 3).join(', ')}`)\n if (sameColumnWith.length > 0) intentPatterns.push(`same_column_with:${sameColumnWith.slice(0, 3).join(', ')}`)\n if (aboveAnchor) intentPatterns.push(`below:${aboveAnchor}`)\n if (belowAnchor) intentPatterns.push(`above:${belowAnchor}`)\n if (sameRowWith.length === 0 && sameColumnWith.length === 0) intentPatterns.push('separate_cluster')\n\n const visualDelta = operation.visualDelta\n const flexDirectionInfo = inferFlexDirection(sameRowWith.length, sameColumnWith.length, visualDelta)\n const flexDirection = flexDirectionInfo.direction\n\n if (recommendedSystem === 'grid') {\n reasons.push('Detected multiple dense row and column clusters; a 2D layout system is likely intentional.')\n return {\n recommendedSystem: 'grid',\n intentPatterns,\n refactorSteps: [\n `Create/ensure a shared container around ${formatAnchorRef(operation.subject)} and related anchors under ${formatAnchorRef(operation.to.parent)}.`,\n `Reorder/reparent elements to satisfy placement ${operation.to.placement.description}.`,\n ],\n styleSteps: [\n `Set ${formatAnchorRef(operation.to.parent)} to grid with explicit template rows/columns for the final layout.`,\n 'Use `gap` for consistent spacing and keep placement structural.',\n ],\n itemSteps: [\n `Set item alignment on ${formatAnchorRef(operation.subject)} with grid self-alignment (` + '`justify-self`/`align-self`).',\n ],\n }\n }\n\n reasons.push(`${flexDirectionInfo.reason} Use a 1D flex layout instead of literal drag replay.`)\n\n let hasStackedCluster = false\n const stackedAnchorLabels = new Set<string>()\n if (flexDirection === 'row' && subjectSnapshot) {\n for (const rowPeer of sameRowNodes) {\n for (const node of childSnapshots) {\n if (node.child === edit.element || node.child === rowPeer.child) continue\n const sameColumnAsPeer = Math.abs(node.centerX - rowPeer.centerX) <= colTolerance\n const verticallySeparated = Math.abs(node.centerY - rowPeer.centerY) > rowTolerance\n if (sameColumnAsPeer && verticallySeparated) {\n hasStackedCluster = true\n stackedAnchorLabels.add(rowPeer.anchorLabel)\n stackedAnchorLabels.add(node.anchorLabel)\n }\n }\n }\n }\n\n const hasBelowCluster = childSnapshots.some((node) => (\n node.child !== edit.element\n && node.centerY - subjectCenterY > rowTolerance * 1.5\n && Math.abs(node.centerY - subjectCenterY) > Math.abs(node.centerX - subjectCenterX)\n ))\n\n const refactorSteps = [\n `Ensure ${formatAnchorRef(operation.subject)} and referenced neighbors share a common container under ${formatAnchorRef(operation.to.parent)}.`,\n `Reparent/reorder nodes so ${formatAnchorRef(operation.subject)} lands ${operation.to.placement.description}.`,\n ]\n if (flexDirection === 'row' && hasStackedCluster) {\n const clusterSample = Array.from(stackedAnchorLabels).slice(0, 3).join(', ')\n refactorSteps.push(`Create a left-side content wrapper for vertically stacked items (${clusterSample}), and keep ${formatAnchorRef(operation.subject)} as the opposite-side sibling.`)\n }\n if (hasBelowCluster) {\n refactorSteps.push('Keep lower content sections in a separate block below the horizontal header row; do not force them into the same row.')\n }\n\n const styleSteps = [\n `Set ${formatAnchorRef(operation.to.parent)} to flex with direction ${flexDirection}.`,\n flexDirection === 'row'\n ? 'Use `justify-content: space-between` and `align-items: flex-start` when the moved element should sit on the opposite edge.'\n : 'Use `justify-content` / `align-items` to establish top-bottom alignment.',\n 'Use `gap` for spacing between siblings.',\n ]\n if (flexDirection === 'row' && hasStackedCluster) {\n styleSteps.push('Set the content wrapper to `display: flex` with `flex-direction: column` and an appropriate vertical gap.')\n }\n\n return {\n recommendedSystem: 'flex',\n intentPatterns,\n refactorSteps,\n styleSteps,\n itemSteps: [\n `Apply item-level alignment (` + '`align-self`' + ` / flex-basis) only when needed for ${formatAnchorRef(operation.subject)}.`,\n 'Do not use absolute positioning, top/left offsets, transforms, or margin hacks to simulate movement.',\n ],\n }\n}\n\ninterface MovePlanEntry {\n edit: SessionEdit\n operation: Omit<MoveOperation, 'operationId'>\n sortKey: string\n}\n\nexport interface MovePlanContext {\n movePlan: MovePlan | null\n intentsByEdit: Map<SessionEdit, MoveIntent>\n noopMoveCount: number\n}\n\nfunction buildMoveEntries(edits: SessionEdit[]): {\n entries: MovePlanEntry[]\n noopMoveCount: number\n} {\n const entries: MovePlanEntry[] = []\n let noopMoveCount = 0\n\n for (const edit of edits) {\n const move = edit.move\n if (!move) continue\n\n const subject = buildAnchorRef(\n getElementDisplayName(edit.element) || edit.locator.tagName,\n edit.locator.domSelector,\n edit.locator.domSource,\n )\n const fromParent = buildAnchorRef(move.fromParentName, move.fromParentSelector, move.fromParentSource)\n const toParent = buildAnchorRef(move.toParentName, move.toParentSelector, move.toParentSource)\n const fromPlacement = buildPlacementFromMove(\n move.fromSiblingBefore,\n move.fromSiblingBeforeSelector,\n move.fromSiblingBeforeSource,\n move.fromSiblingAfter,\n move.fromSiblingAfterSelector,\n move.fromSiblingAfterSource,\n )\n const toPlacement = buildPlacementFromMove(\n move.toSiblingBefore,\n move.toSiblingBeforeSelector,\n move.toSiblingBeforeSource,\n move.toSiblingAfter,\n move.toSiblingAfterSelector,\n move.toSiblingAfterSource,\n )\n\n const reasons: string[] = []\n const classification = classifyMove(move)\n if (classification === 'noop') {\n noopMoveCount++\n continue\n }\n\n const interactionMode = move.mode ?? 'free'\n const visualDelta = toRoundedVisualDelta(move)\n if (visualDelta) {\n reasons.push(`Non-zero visual delta detected (${visualDelta.x}px, ${visualDelta.y}px).`)\n }\n\n const structuralChange = hasStructuralChange(move)\n if (structuralChange) reasons.push('Anchor placement changed between source and target.')\n else reasons.push('No anchor placement change; treating movement as layout intent translation.')\n\n const operationBase: Omit<MoveOperation, 'operationId'> = {\n classification,\n interactionMode,\n subject,\n from: { parent: fromParent, placement: fromPlacement },\n to: { parent: toParent, placement: toPlacement },\n ...(visualDelta ? { visualDelta } : {}),\n confidence: classification === 'existing_layout_move'\n ? 'high'\n : structuralChange\n ? 'medium'\n : 'high',\n reasons,\n }\n\n if (classification === 'layout_refactor') {\n operationBase.layoutPrescription = inferLayoutPrescription(edit, operationBase, reasons)\n }\n\n const sortSource = subject.source?.file\n ? `${subject.source.file}:${subject.source.line ?? 0}:${subject.source.column ?? 0}`\n : ''\n const sortKey = [\n sortSource,\n anchorKey(subject),\n anchorKey(toParent),\n toPlacement.description,\n ].join('|')\n entries.push({ edit, operation: operationBase, sortKey })\n }\n\n entries.sort((a, b) => a.sortKey.localeCompare(b.sortKey))\n return { entries, noopMoveCount }\n}\n\nexport function buildMovePlanContext(\n edits: SessionEdit[],\n _domContext?: unknown\n): MovePlanContext {\n const { entries, noopMoveCount } = buildMoveEntries(edits)\n if (entries.length === 0) {\n return {\n movePlan: null,\n intentsByEdit: new Map(),\n noopMoveCount,\n }\n }\n\n const operations: MoveOperation[] = []\n const intentsByEdit = new Map<SessionEdit, MoveIntent>()\n for (let i = 0; i < entries.length; i++) {\n const operationId = `op-${i + 1}`\n const operation: MoveOperation = { operationId, ...entries[i].operation }\n operations.push(operation)\n intentsByEdit.set(entries[i].edit, operation)\n }\n\n const affectedContainerMap = new Map<string, AnchorRef>()\n for (const operation of operations) {\n affectedContainerMap.set(anchorKey(operation.from.parent), operation.from.parent)\n affectedContainerMap.set(anchorKey(operation.to.parent), operation.to.parent)\n }\n\n const orderingConstraints = operations\n .filter(op => op.classification === 'existing_layout_move')\n .map(op => `${op.operationId}: place ${formatAnchorRef(op.subject)} ${op.to.placement.description} in ${formatAnchorRef(op.to.parent)}.`)\n\n const notes: string[] = []\n if (noopMoveCount > 0) notes.push(`Excluded ${noopMoveCount} no-op move(s).`)\n if (operations.some(op => op.classification === 'layout_refactor')) {\n notes.push('Layout refactor operations include best-practice flex/grid prescriptions.')\n }\n\n return {\n movePlan: {\n operations,\n affectedContainers: Array.from(affectedContainerMap.values()),\n orderingConstraints,\n notes,\n },\n intentsByEdit,\n noopMoveCount,\n }\n}\n\nexport function buildMovePlan(edits: SessionEdit[], domContext?: unknown): MovePlan {\n const context = buildMovePlanContext(edits, domContext)\n return context.movePlan ?? {\n operations: [],\n affectedContainers: [],\n orderingConstraints: [],\n notes: context.noopMoveCount > 0 ? [`Excluded ${context.noopMoveCount} no-op move(s).`] : [],\n }\n}\n\nexport function getMoveIntentForEdit(\n edit: SessionEdit,\n context?: MovePlanContext | null\n): MoveIntent | null {\n if (!edit.move) return null\n if (context?.intentsByEdit.has(edit)) return context.intentsByEdit.get(edit) ?? null\n const singleContext = buildMovePlanContext([edit])\n return singleContext.intentsByEdit.get(edit) ?? null\n}\n\nfunction buildMoveInstructionFromIntent(intent: MoveIntent): string {\n if (intent.classification === 'existing_layout_move') {\n return `Apply as a structural move in code: place ${formatAnchorRef(intent.subject)} ${intent.to.placement.description} in ${formatAnchorRef(intent.to.parent)}.`\n }\n const system = intent.layoutPrescription?.recommendedSystem ?? 'flex'\n return `Treat this as a ${system} layout refactor. Implement the listed structure/style steps in source code instead of drag replay.`\n}\n\nfunction formatMoveType(classification: MoveClassification): 'structural_move' | 'layout_refactor' {\n return classification === 'existing_layout_move' ? 'structural_move' : 'layout_refactor'\n}\n\nfunction buildMoveExportLines(intent: MoveIntent): string[] {\n const moveType = formatMoveType(intent.classification)\n const implementationSteps: string[] = []\n if (intent.classification === 'existing_layout_move') {\n implementationSteps.push(`Reorder/reparent ${formatAnchorRef(intent.subject)} to ${intent.to.placement.description} in ${formatAnchorRef(intent.to.parent)}.`)\n } else {\n const prescription = intent.layoutPrescription\n if (prescription) {\n implementationSteps.push(...prescription.refactorSteps)\n implementationSteps.push(...prescription.styleSteps)\n implementationSteps.push(...prescription.itemSteps)\n }\n }\n\n const lines: string[] = [\n 'moved:',\n `id: ${intent.operationId}`,\n `type: ${moveType}`,\n `subject: ${formatAnchorRef(intent.subject, '(unknown)')}`,\n `parent: ${formatAnchorRef(intent.to.parent, '(unknown)')}`,\n `current_anchor: ${intent.from.placement.description}`,\n `target_anchor: ${intent.to.placement.description}`,\n ...(intent.visualDelta\n ? [`visual_hint: ${intent.visualDelta.x}px horizontal, ${intent.visualDelta.y}px vertical`]\n : []),\n ]\n\n if (intent.layoutPrescription) {\n lines.push(`recommended_layout: ${intent.layoutPrescription.recommendedSystem}`)\n }\n\n lines.push('implementation_steps:')\n for (const step of implementationSteps) {\n lines.push(` - ${step}`)\n }\n\n lines.push('guardrails:')\n lines.push(' - Do not simulate movement with absolute positioning, left/top offsets, transform, or margin hacks.')\n lines.push(`instruction: ${buildMoveInstructionFromIntent(intent)}`)\n return lines\n}\n\ninterface SessionExportOptions {\n movePlanContext?: MovePlanContext | null\n includeMovePlanHeader?: boolean\n}\n\nexport interface ExportContentProfile {\n hasCssEdits: boolean\n hasTextEdits: boolean\n hasMoves: boolean\n hasComments: boolean\n}\n\nexport function getExportContentProfile(\n edits: SessionEdit[],\n comments: Comment[],\n movePlanOrContext?: MovePlan | MovePlanContext | null\n): ExportContentProfile {\n const moveOpCount = movePlanOrContext\n ? ('operations' in movePlanOrContext\n ? movePlanOrContext.operations.length\n : (movePlanOrContext.movePlan?.operations.length ?? 0))\n : (buildMovePlanContext(edits).movePlan?.operations.length ?? 0)\n\n return {\n hasCssEdits: edits.some(e => Object.keys(e.pendingStyles).length > 0),\n hasTextEdits: edits.some(e => e.textEdit != null),\n hasMoves: moveOpCount > 0,\n hasComments: comments.length > 0,\n }\n}\n\nexport function buildExportInstruction(profile: ExportContentProfile): string {\n const { hasCssEdits, hasTextEdits, hasMoves, hasComments } = profile\n\n if (!hasCssEdits && !hasTextEdits && !hasMoves && !hasComments) return ''\n\n if (!hasCssEdits && !hasTextEdits && !hasMoves) {\n return hasComments\n ? 'Address this feedback on the UI. Use the provided source location and selector to find each element in the codebase.'\n : ''\n }\n\n const parts: string[] = []\n if (hasCssEdits) parts.push('Apply the CSS changes to the targeted elements using the project\\'s existing styling approach (Tailwind, CSS modules, etc.). Map values to existing CSS variables, design tokens, or utility classes already used in the project whenever possible.')\n if (hasTextEdits) parts.push('Update the text content as specified.')\n if (hasMoves) parts.push('Implement the move plan below directly in source code. For `structural_move`, reorder/reparent elements using the target anchors. For `layout_refactor`, apply the listed flex/grid refactor steps. Do NOT simulate movement with absolute positioning, left/top offsets, transform, or margin hacks.')\n if (hasComments) parts.push('Address the comments on the relevant elements.')\n\n return `${parts.join(' ')} Use the provided source locations, selectors, and context HTML to locate each element in the codebase.`\n}\n\nexport function buildSessionExport(\n edits: SessionEdit[],\n comments: Comment[] = [],\n options?: SessionExportOptions\n): string {\n const blocks: string[] = []\n const planContext = options?.movePlanContext ?? buildMovePlanContext(edits)\n const movePlan = planContext.movePlan\n const includeMovePlanHeader = options?.includeMovePlanHeader !== false\n\n if (includeMovePlanHeader && movePlan && movePlan.operations.length > 0) {\n const planLines: string[] = [\n '=== LAYOUT MOVE PLAN ===',\n `operations: ${movePlan.operations.length}`,\n ]\n if (movePlan.affectedContainers.length > 0) {\n planLines.push('containers:')\n for (const container of movePlan.affectedContainers) {\n planLines.push(` - ${formatAnchorRef(container, '(unknown)')}`)\n }\n }\n if (movePlan.orderingConstraints.length > 0) {\n planLines.push('structural_constraints:')\n for (const constraint of movePlan.orderingConstraints) {\n planLines.push(` - ${constraint}`)\n }\n }\n if (movePlan.notes.length > 0) {\n planLines.push('plan_notes:')\n for (const note of movePlan.notes) {\n planLines.push(` - ${note}`)\n }\n }\n blocks.push(planLines.join('\\n'))\n }\n\n for (const edit of edits) {\n const moveIntent = getMoveIntentForEdit(edit, planContext)\n const hasMove = Boolean(moveIntent)\n const hasStyleOrText = Object.keys(edit.pendingStyles).length > 0 || edit.textEdit != null\n if (!hasMove && !hasStyleOrText) continue\n\n const block = hasMove\n ? buildEditExportWithOptions(edit.locator, edit.pendingStyles, edit.textEdit, { skipContext: true })\n : buildEditExport(edit.locator, edit.pendingStyles, edit.textEdit)\n\n let moveBlock = ''\n if (moveIntent) {\n moveBlock = `\\n${buildMoveExportLines(moveIntent).join('\\n')}`\n }\n blocks.push(block + moveBlock)\n }\n\n for (const comment of comments) {\n blocks.push(buildCommentExport(comment.locator, comment.text, comment.replies))\n }\n\n return blocks.join('\\n\\n---\\n\\n')\n}\n\nexport type {\n ElementInfo,\n CSSPropertyValue,\n SpacingProperties,\n BorderRadiusProperties,\n BorderStyle,\n BorderProperties,\n FlexProperties,\n DirectEditState,\n SpacingPropertyKey,\n BorderRadiusPropertyKey,\n BorderPropertyKey,\n FlexPropertyKey,\n MeasurementLine,\n MeasurementState,\n ColorValue,\n ColorProperties,\n ColorPropertyKey,\n SizingProperties,\n SizingPropertyKey,\n SizingMode,\n SizingValue,\n TypographyProperties,\n TypographyPropertyKey,\n ReactComponentFrame,\n ElementLocator,\n DragState,\n DropTarget,\n DropIndicator,\n} from './types'\n","import type { CSSPropertyValue } from '../types'\n\nexport function parsePropertyValue(value: string): CSSPropertyValue {\n const raw = value.trim()\n const match = raw.match(/^(-?\\d*\\.?\\d+)(px|rem|em|vh|vw|%)?$/)\n\n if (match) {\n return {\n numericValue: parseFloat(match[1]),\n unit: (match[2] as CSSPropertyValue['unit']) || 'px',\n raw,\n }\n }\n\n return {\n numericValue: 0,\n unit: 'px',\n raw,\n }\n}\n\nexport function formatPropertyValue(value: CSSPropertyValue): string {\n if (value.raw === 'auto' || value.raw === 'inherit' || value.raw === 'initial') {\n return value.raw\n }\n return `${value.numericValue}${value.unit}`\n}\n","import { useSyncExternalStore } from 'react'\n\ntype CanvasSnapshot = { active: boolean; zoom: number; panX: number; panY: number }\n\nconst DEFAULT: CanvasSnapshot = { active: false, zoom: 1, panX: 0, panY: 0 }\n\nlet snapshot: CanvasSnapshot = DEFAULT\nconst listeners = new Set<() => void>()\nlet ownerCount = 0\n\nlet bodyOffset = { x: 0, y: 0 }\nexport function getBodyOffset() { return bodyOffset }\nexport function setBodyOffset(o: { x: number; y: number }) { bodyOffset = o }\n\nexport function getCanvasSnapshot(): CanvasSnapshot {\n return snapshot\n}\n\nexport function setCanvasSnapshot(next: CanvasSnapshot) {\n snapshot = next\n listeners.forEach((cb) => cb())\n}\n\nexport function registerCanvasStoreOwner(): () => void {\n ownerCount += 1\n if (ownerCount > 1 && (typeof process === 'undefined' || process.env.NODE_ENV !== 'test')) {\n console.warn('[made-refine] multiple DirectEditProvider instances share canvas-store globals')\n }\n return () => {\n ownerCount = Math.max(0, ownerCount - 1)\n }\n}\n\nfunction subscribe(cb: () => void) {\n listeners.add(cb)\n return () => {\n listeners.delete(cb)\n }\n}\n\n/** Synchronous canvas state — no rAF lag. Use for overlays that must track the DOM transform exactly. */\nexport function useCanvasSnapshot(): CanvasSnapshot {\n return useSyncExternalStore(subscribe, getCanvasSnapshot, () => DEFAULT)\n}\n","import type { ElementInfo, MeasurementLine, Guideline } from '../types'\nimport { isTextElement } from './element-selection'\nimport { getCanvasSnapshot, getBodyOffset } from '../canvas-store'\n\nexport function getZoomScale(): number {\n const snap = getCanvasSnapshot()\n return snap.active ? snap.zoom : 1\n}\n\nexport function getElementInfo(element: HTMLElement): ElementInfo {\n const computed = window.getComputedStyle(element)\n const parentElement = element.parentElement\n\n const isFlexContainer = computed.display === 'flex' || computed.display === 'inline-flex'\n\n let isFlexItem = false\n if (parentElement) {\n const parentComputed = window.getComputedStyle(parentElement)\n isFlexItem = parentComputed.display === 'flex' || parentComputed.display === 'inline-flex'\n }\n\n return {\n tagName: element.tagName.toLowerCase(),\n id: element.id || null,\n classList: Array.from(element.classList),\n isFlexContainer,\n isFlexItem,\n isTextElement: isTextElement(element),\n parentElement,\n hasChildren: element.children.length > 0,\n }\n}\n\ninterface DimensionDisplay {\n width: string\n height: string\n}\n\nfunction isFitSizing(element: HTMLElement, dimension: 'width' | 'height'): boolean {\n const computed = window.getComputedStyle(element)\n const inlineValue = element.style[dimension]\n\n if (inlineValue === 'auto') return true\n\n const computedValue = computed[dimension]\n\n if (!inlineValue) {\n const parent = element.parentElement\n if (parent) {\n const parentComputed = window.getComputedStyle(parent)\n if (parentComputed.display === 'flex' || parentComputed.display === 'inline-flex') {\n const flexBasis = computed.flexBasis\n const flexGrow = computed.flexGrow\n if (flexBasis === 'auto' && flexGrow === '0') {\n return true\n }\n }\n }\n\n if (dimension === 'width') {\n if (computed.display === 'block' && !inlineValue) {\n return false\n }\n if (\n computed.display === 'inline-block' ||\n computed.display === 'inline-flex' ||\n computed.display === 'inline'\n ) {\n return true\n }\n }\n\n if (dimension === 'height') {\n return !inlineValue\n }\n }\n\n if (computedValue.includes('fit-content') || computedValue.includes('max-content')) {\n return true\n }\n\n return false\n}\n\nexport function getDimensionDisplay(element: HTMLElement): DimensionDisplay {\n const width = Math.round(element.offsetWidth)\n const height = Math.round(element.offsetHeight)\n\n const widthIsFit = isFitSizing(element, 'width')\n const heightIsFit = isFitSizing(element, 'height')\n\n return {\n width: widthIsFit ? `Fit ${width}` : `${width}`,\n height: heightIsFit ? `Fit ${height}` : `${height}`,\n }\n}\n\n\nexport function calculateParentMeasurements(element: HTMLElement, container?: HTMLElement): MeasurementLine[] {\n const parent = container ?? element.parentElement\n if (!parent) return []\n\n const elementRect = element.getBoundingClientRect()\n const parentRect = parent.getBoundingClientRect()\n\n // Use clientLeft/clientTop for reliable border widths, clientWidth/clientHeight\n // for inner dimensions (handles scrollbars correctly)\n const paddingBoxLeft = parentRect.left + parent.clientLeft\n const paddingBoxTop = parentRect.top + parent.clientTop\n const paddingBoxRight = parentRect.left + parent.clientLeft + parent.clientWidth\n const paddingBoxBottom = parentRect.top + parent.clientTop + parent.clientHeight\n\n let parentInnerLeft: number\n let parentInnerTop: number\n let parentInnerRight: number\n let parentInnerBottom: number\n\n if (container) {\n // Ancestor case: measure from padding-box (inside border, outside padding).\n // The ancestor's padding doesn't directly position the child — intermediate\n // elements do — so the visually correct edge is inside the border only.\n parentInnerLeft = paddingBoxLeft\n parentInnerTop = paddingBoxTop\n parentInnerRight = paddingBoxRight\n parentInnerBottom = paddingBoxBottom\n } else {\n // Direct parent case: measure from content-box (inside border and padding).\n // The parent's padding IS the gap between its edge and the child's layout area.\n const parentStyles = window.getComputedStyle(parent)\n parentInnerLeft = paddingBoxLeft + (parseFloat(parentStyles.paddingLeft) || 0)\n parentInnerTop = paddingBoxTop + (parseFloat(parentStyles.paddingTop) || 0)\n parentInnerRight = paddingBoxRight - (parseFloat(parentStyles.paddingRight) || 0)\n parentInnerBottom = paddingBoxBottom - (parseFloat(parentStyles.paddingBottom) || 0)\n }\n\n const zoom = getZoomScale()\n const measurements: MeasurementLine[] = []\n\n const topDistance = Math.round((elementRect.top - parentInnerTop) / zoom)\n if (topDistance > 0) {\n const midX = elementRect.left + elementRect.width / 2\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: parentInnerTop,\n x2: midX,\n y2: elementRect.top,\n distance: topDistance,\n labelPosition: { x: midX, y: (parentInnerTop + elementRect.top) / 2 },\n })\n }\n\n const bottomDistance = Math.round((parentInnerBottom - elementRect.bottom) / zoom)\n if (bottomDistance > 0) {\n const midX = elementRect.left + elementRect.width / 2\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: elementRect.bottom,\n x2: midX,\n y2: parentInnerBottom,\n distance: bottomDistance,\n labelPosition: { x: midX, y: (elementRect.bottom + parentInnerBottom) / 2 },\n })\n }\n\n const leftDistance = Math.round((elementRect.left - parentInnerLeft) / zoom)\n if (leftDistance > 0) {\n const midY = elementRect.top + elementRect.height / 2\n measurements.push({\n direction: 'horizontal',\n x1: parentInnerLeft,\n y1: midY,\n x2: elementRect.left,\n y2: midY,\n distance: leftDistance,\n labelPosition: { x: (parentInnerLeft + elementRect.left) / 2, y: midY },\n })\n }\n\n const rightDistance = Math.round((parentInnerRight - elementRect.right) / zoom)\n if (rightDistance > 0) {\n const midY = elementRect.top + elementRect.height / 2\n measurements.push({\n direction: 'horizontal',\n x1: elementRect.right,\n y1: midY,\n x2: parentInnerRight,\n y2: midY,\n distance: rightDistance,\n labelPosition: { x: (elementRect.right + parentInnerRight) / 2, y: midY },\n })\n }\n\n return measurements\n}\n\nexport function calculateElementMeasurements(\n from: HTMLElement,\n to: HTMLElement\n): MeasurementLine[] {\n const fromRect = from.getBoundingClientRect()\n const toRect = to.getBoundingClientRect()\n const zoom = getZoomScale()\n const measurements: MeasurementLine[] = []\n\n const horizontalOverlap =\n fromRect.left < toRect.right && fromRect.right > toRect.left\n const verticalOverlap =\n fromRect.top < toRect.bottom && fromRect.bottom > toRect.top\n\n if (verticalOverlap) {\n const overlapTop = Math.max(fromRect.top, toRect.top)\n const overlapBottom = Math.min(fromRect.bottom, toRect.bottom)\n const midY = (overlapTop + overlapBottom) / 2\n\n if (fromRect.right <= toRect.left) {\n const distance = Math.round((toRect.left - fromRect.right) / zoom)\n measurements.push({\n direction: 'horizontal',\n x1: fromRect.right,\n y1: midY,\n x2: toRect.left,\n y2: midY,\n distance,\n labelPosition: { x: (fromRect.right + toRect.left) / 2, y: midY },\n })\n } else if (fromRect.left >= toRect.right) {\n const distance = Math.round((fromRect.left - toRect.right) / zoom)\n measurements.push({\n direction: 'horizontal',\n x1: toRect.right,\n y1: midY,\n x2: fromRect.left,\n y2: midY,\n distance,\n labelPosition: { x: (toRect.right + fromRect.left) / 2, y: midY },\n })\n }\n }\n\n if (horizontalOverlap) {\n const overlapLeft = Math.max(fromRect.left, toRect.left)\n const overlapRight = Math.min(fromRect.right, toRect.right)\n const midX = (overlapLeft + overlapRight) / 2\n\n if (fromRect.bottom <= toRect.top) {\n const distance = Math.round((toRect.top - fromRect.bottom) / zoom)\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: fromRect.bottom,\n x2: midX,\n y2: toRect.top,\n distance,\n labelPosition: { x: midX, y: (fromRect.bottom + toRect.top) / 2 },\n })\n } else if (fromRect.top >= toRect.bottom) {\n const distance = Math.round((fromRect.top - toRect.bottom) / zoom)\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: toRect.bottom,\n x2: midX,\n y2: fromRect.top,\n distance,\n labelPosition: { x: midX, y: (toRect.bottom + fromRect.top) / 2 },\n })\n }\n }\n\n if (!horizontalOverlap && !verticalOverlap) {\n const fromCenterX = fromRect.left + fromRect.width / 2\n const fromCenterY = fromRect.top + fromRect.height / 2\n const toCenterX = toRect.left + toRect.width / 2\n const toCenterY = toRect.top + toRect.height / 2\n\n const hDistance = toCenterX > fromCenterX\n ? Math.round((toRect.left - fromRect.right) / zoom)\n : Math.round((fromRect.left - toRect.right) / zoom)\n\n if (hDistance > 0) {\n const startX = toCenterX > fromCenterX ? fromRect.right : fromRect.left\n const endX = toCenterX > fromCenterX ? toRect.left : toRect.right\n const y = (fromCenterY + toCenterY) / 2\n measurements.push({\n direction: 'horizontal',\n x1: startX,\n y1: y,\n x2: endX,\n y2: y,\n distance: hDistance,\n labelPosition: { x: (startX + endX) / 2, y },\n })\n }\n\n const vDistance = toCenterY > fromCenterY\n ? Math.round((toRect.top - fromRect.bottom) / zoom)\n : Math.round((fromRect.top - toRect.bottom) / zoom)\n\n if (vDistance > 0) {\n const x = (fromCenterX + toCenterX) / 2\n const startY = toCenterY > fromCenterY ? fromRect.bottom : fromRect.top\n const endY = toCenterY > fromCenterY ? toRect.top : toRect.bottom\n measurements.push({\n direction: 'vertical',\n x1: x,\n y1: startY,\n x2: x,\n y2: endY,\n distance: vDistance,\n labelPosition: { x, y: (startY + endY) / 2 },\n })\n }\n }\n\n return measurements\n}\n\nconst GUIDELINE_PROXIMITY = 80\n\nexport function calculateGuidelineMeasurements(\n element: HTMLElement,\n guidelines: Guideline[],\n mousePosition?: { x: number; y: number } | null,\n): MeasurementLine[] {\n if (guidelines.length === 0) return []\n\n const snap = getCanvasSnapshot()\n const zoom = snap.active ? snap.zoom : 1\n const rect = element.getBoundingClientRect()\n const measurements: MeasurementLine[] = []\n\n for (const g of guidelines) {\n let viewportPos: number\n if (snap.active) {\n const pan = g.orientation === 'horizontal' ? snap.panY : snap.panX\n const bo = g.orientation === 'horizontal' ? getBodyOffset().y : getBodyOffset().x\n viewportPos = bo + (g.position - bo + pan) * zoom\n } else {\n const scroll = g.orientation === 'horizontal' ? window.scrollY : window.scrollX\n viewportPos = g.position - scroll\n }\n\n if (g.orientation === 'horizontal') {\n const midX = rect.left + rect.width / 2\n\n if (mousePosition && Math.abs(mousePosition.y - viewportPos) > GUIDELINE_PROXIMITY) continue\n\n if (viewportPos < rect.top) {\n const distance = Math.round((rect.top - viewportPos) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: viewportPos,\n x2: midX,\n y2: rect.top,\n distance,\n labelPosition: { x: midX, y: (viewportPos + rect.top) / 2 },\n })\n }\n } else if (viewportPos > rect.bottom) {\n const distance = Math.round((viewportPos - rect.bottom) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: rect.bottom,\n x2: midX,\n y2: viewportPos,\n distance,\n labelPosition: { x: midX, y: (rect.bottom + viewportPos) / 2 },\n })\n }\n }\n } else {\n const midY = rect.top + rect.height / 2\n\n if (mousePosition && Math.abs(mousePosition.x - viewportPos) > GUIDELINE_PROXIMITY) continue\n\n if (viewportPos < rect.left) {\n const distance = Math.round((rect.left - viewportPos) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'horizontal',\n x1: viewportPos,\n y1: midY,\n x2: rect.left,\n y2: midY,\n distance,\n labelPosition: { x: (viewportPos + rect.left) / 2, y: midY },\n })\n }\n } else if (viewportPos > rect.right) {\n const distance = Math.round((viewportPos - rect.right) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'horizontal',\n x1: rect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K,aAAa,EAAE,SAAS,KAAK,KAAK,YAAY;AACtF,QAAI,CAAC,WAAW,CAAC,eAAgB;AAEjC,UAAM,QAAQ,UACV,2BAA2B,KAAK,SAAS,KAAK,eAAe,KAAK,UAAU,EAAE,aAAa,KAAK,CAAC,IACjG,gBAAgB,KAAK,SAAS,KAAK,eAAe,KAAK,QAAQ;AAEnE,QAAI,YAAY;AAChB,QAAI,YAAY;AACd,kBAAY;AAAA,EAAK,qBAAqB,UAAU,EAAE,KAAK,IAAI,CAAC;AAAA,IAC9D;AACA,WAAO,KAAK,QAAQ,SAAS;AAAA,EAC/B;AAEA,aAAW,WAAW,UAAU;AAC9B,WAAO,KAAK,mBAAmB,QAAQ,SAAS,QAAQ,MAAM,QAAQ,OAAO,CAAC;AAAA,EAChF;AAEA,SAAO,OAAO,KAAK,aAAa;AAClC;","names":["isTextElement","isTextElement","numeric","isFlexContainer","containerRect","snapshot"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils.ts","../src/utils/css-value.ts","../src/canvas-store.ts","../src/utils/measurements.ts","../src/utils/react-fiber.ts"],"sourcesContent":["import type {\n CSSPropertyValue,\n SpacingProperties,\n BorderRadiusProperties,\n BorderStyle,\n BorderProperties,\n FlexProperties,\n SizingProperties,\n SizingValue,\n SizingMode,\n SpacingPropertyKey,\n BorderRadiusPropertyKey,\n BorderPropertyKey,\n FlexPropertyKey,\n SizingPropertyKey,\n TypographyPropertyKey,\n TypographyProperties,\n ElementInfo,\n ReactComponentFrame,\n ElementLocator,\n DomSourceLocation,\n ColorValue,\n ColorProperties,\n ColorPropertyKey,\n MeasurementLine,\n Guideline,\n DropIndicator,\n SessionEdit,\n SessionItem,\n AnchorRef,\n PlacementRef,\n MoveClassification,\n MoveOperation,\n MoveIntent,\n MovePlan,\n LayoutPrescription,\n Comment,\n} from './types'\n\nexport { parsePropertyValue, formatPropertyValue } from './utils/css-value'\nimport { parsePropertyValue } from './utils/css-value'\nimport { getCanvasSnapshot, getBodyOffset } from './canvas-store'\nimport { getZoomScale } from './utils/measurements'\nimport {\n getComponentProps,\n getCallSiteSource,\n deriveDefinitionSource,\n isComponentPrimitivePath,\n classifyComponentFiber,\n} from './utils/react-fiber'\n\nexport function clamp(value: number, min: number, max: number): number {\n if (!Number.isFinite(value)) return min\n if (max < min) return min\n return Math.max(min, Math.min(max, value))\n}\n\nexport function isInputFocused(): boolean {\n let active: Element | null = document.activeElement\n while (active?.shadowRoot?.activeElement) {\n active = active.shadowRoot.activeElement\n }\n return (\n active instanceof HTMLInputElement ||\n active instanceof HTMLTextAreaElement ||\n (active instanceof HTMLElement && active.isContentEditable)\n )\n}\n\ndeclare global {\n interface Window {\n __DIRECT_EDIT_DEVTOOLS__?: {\n getFiberForElement: (element: HTMLElement) => unknown | null\n hasHook?: boolean\n }\n }\n}\n\nexport function getComputedStyles(element: HTMLElement): {\n spacing: SpacingProperties\n borderRadius: BorderRadiusProperties\n flex: FlexProperties\n} {\n const computed = window.getComputedStyle(element)\n\n return {\n spacing: {\n paddingTop: parsePropertyValue(computed.paddingTop),\n paddingRight: parsePropertyValue(computed.paddingRight),\n paddingBottom: parsePropertyValue(computed.paddingBottom),\n paddingLeft: parsePropertyValue(computed.paddingLeft),\n marginTop: parsePropertyValue(computed.marginTop),\n marginRight: parsePropertyValue(computed.marginRight),\n marginBottom: parsePropertyValue(computed.marginBottom),\n marginLeft: parsePropertyValue(computed.marginLeft),\n gap: parsePropertyValue(computed.gap || '0px'),\n },\n borderRadius: {\n borderTopLeftRadius: parsePropertyValue(computed.borderTopLeftRadius),\n borderTopRightRadius: parsePropertyValue(computed.borderTopRightRadius),\n borderBottomRightRadius: parsePropertyValue(computed.borderBottomRightRadius),\n borderBottomLeftRadius: parsePropertyValue(computed.borderBottomLeftRadius),\n },\n flex: {\n display: computed.display,\n flexDirection: computed.flexDirection as FlexProperties['flexDirection'],\n justifyContent: computed.justifyContent,\n alignItems: computed.alignItems,\n },\n }\n}\n\nexport function getComputedBorderStyles(element: HTMLElement): BorderProperties {\n const computed = window.getComputedStyle(element)\n\n const topStyle = computed.borderTopStyle as BorderStyle\n const rightStyle = computed.borderRightStyle as BorderStyle\n const bottomStyle = computed.borderBottomStyle as BorderStyle\n const leftStyle = computed.borderLeftStyle as BorderStyle\n\n const topWidth = parsePropertyValue(computed.borderTopWidth)\n const rightWidth = parsePropertyValue(computed.borderRightWidth)\n const bottomWidth = parsePropertyValue(computed.borderBottomWidth)\n const leftWidth = parsePropertyValue(computed.borderLeftWidth)\n\n return {\n borderTopStyle: topStyle,\n borderTopWidth: topWidth,\n borderRightStyle: rightStyle,\n borderRightWidth: rightWidth,\n borderBottomStyle: bottomStyle,\n borderBottomWidth: bottomWidth,\n borderLeftStyle: leftStyle,\n borderLeftWidth: leftWidth,\n }\n}\n\n/** CSS properties captured before editing so resetToOriginal can restore them. */\nexport const ORIGINAL_STYLE_PROPS = [\n 'padding-top',\n 'padding-right',\n 'padding-bottom',\n 'padding-left',\n 'padding',\n 'margin-top',\n 'margin-right',\n 'margin-bottom',\n 'margin-left',\n 'margin',\n 'gap',\n 'border-radius',\n 'border-top-left-radius',\n 'border-top-right-radius',\n 'border-bottom-right-radius',\n 'border-bottom-left-radius',\n 'border',\n 'border-style',\n 'border-width',\n 'border-top-style',\n 'border-top-width',\n 'border-right-style',\n 'border-right-width',\n 'border-bottom-style',\n 'border-bottom-width',\n 'border-left-style',\n 'border-left-width',\n 'display',\n 'flex-direction',\n 'justify-content',\n 'align-items',\n 'width',\n 'height',\n 'background-color',\n 'background',\n 'color',\n 'border-color',\n 'outline-color',\n 'outline-style',\n 'outline-width',\n 'box-shadow',\n 'font-family',\n 'font-weight',\n 'font-size',\n 'line-height',\n 'letter-spacing',\n 'text-align',\n] as const\n\nexport function getOriginalInlineStyles(element: HTMLElement): Record<string, string> {\n const styles: Record<string, string> = {}\n\n for (const prop of ORIGINAL_STYLE_PROPS) {\n const value = element.style.getPropertyValue(prop)\n if (value) {\n styles[prop] = value\n }\n }\n\n return styles\n}\n\nconst spacingScale: Record<number, string> = { 0: '0', 1: 'px', 2: '0.5', 4: '1', 8: '2', 12: '3', 16: '4', 20: '5', 24: '6', 32: '8' }\n\nconst tailwindClassMap: Record<string, { prefix: string; scale: Record<number, string> }> = {\n padding: { prefix: 'p', scale: spacingScale },\n 'padding-inline': { prefix: 'px', scale: spacingScale },\n 'padding-block': { prefix: 'py', scale: spacingScale },\n 'padding-top': { prefix: 'pt', scale: spacingScale },\n 'padding-right': { prefix: 'pr', scale: spacingScale },\n 'padding-bottom': { prefix: 'pb', scale: spacingScale },\n 'padding-left': { prefix: 'pl', scale: spacingScale },\n margin: { prefix: 'm', scale: spacingScale },\n 'margin-inline': { prefix: 'mx', scale: spacingScale },\n 'margin-block': { prefix: 'my', scale: spacingScale },\n 'margin-top': { prefix: 'mt', scale: spacingScale },\n 'margin-right': { prefix: 'mr', scale: spacingScale },\n 'margin-bottom': { prefix: 'mb', scale: spacingScale },\n 'margin-left': { prefix: 'ml', scale: spacingScale },\n gap: { prefix: 'gap', scale: spacingScale },\n 'border-width': {\n prefix: 'border',\n scale: { 0: '0', 1: '', 2: '2', 4: '4', 8: '8' },\n },\n 'border-top-width': {\n prefix: 'border-t',\n scale: { 0: '0', 1: '', 2: '2', 4: '4', 8: '8' },\n },\n 'border-right-width': {\n prefix: 'border-r',\n scale: { 0: '0', 1: '', 2: '2', 4: '4', 8: '8' },\n },\n 'border-bottom-width': {\n prefix: 'border-b',\n scale: { 0: '0', 1: '', 2: '2', 4: '4', 8: '8' },\n },\n 'border-left-width': {\n prefix: 'border-l',\n scale: { 0: '0', 1: '', 2: '2', 4: '4', 8: '8' },\n },\n 'border-radius': {\n prefix: 'rounded',\n scale: { 0: 'none', 2: 'sm', 4: '', 6: 'md', 8: 'lg', 12: 'xl', 16: '2xl', 24: '3xl', 9999: 'full' },\n },\n 'border-top-left-radius': {\n prefix: 'rounded-tl',\n scale: { 0: 'none', 2: 'sm', 4: '', 6: 'md', 8: 'lg', 12: 'xl', 16: '2xl', 24: '3xl', 9999: 'full' },\n },\n 'border-top-right-radius': {\n prefix: 'rounded-tr',\n scale: { 0: 'none', 2: 'sm', 4: '', 6: 'md', 8: 'lg', 12: 'xl', 16: '2xl', 24: '3xl', 9999: 'full' },\n },\n 'border-bottom-right-radius': {\n prefix: 'rounded-br',\n scale: { 0: 'none', 2: 'sm', 4: '', 6: 'md', 8: 'lg', 12: 'xl', 16: '2xl', 24: '3xl', 9999: 'full' },\n },\n 'border-bottom-left-radius': {\n prefix: 'rounded-bl',\n scale: { 0: 'none', 2: 'sm', 4: '', 6: 'md', 8: 'lg', 12: 'xl', 16: '2xl', 24: '3xl', 9999: 'full' },\n },\n}\n\nconst flexDirectionMap: Record<string, string> = {\n row: 'flex-row',\n 'row-reverse': 'flex-row-reverse',\n column: 'flex-col',\n 'column-reverse': 'flex-col-reverse',\n}\n\nconst justifyContentMap: Record<string, string> = {\n 'flex-start': 'justify-start',\n 'flex-end': 'justify-end',\n center: 'justify-center',\n 'space-between': 'justify-between',\n 'space-around': 'justify-around',\n 'space-evenly': 'justify-evenly',\n start: 'justify-start',\n end: 'justify-end',\n}\n\nconst alignItemsMap: Record<string, string> = {\n 'flex-start': 'items-start',\n 'flex-end': 'items-end',\n center: 'items-center',\n baseline: 'items-baseline',\n stretch: 'items-stretch',\n start: 'items-start',\n end: 'items-end',\n}\n\nfunction getExactScaleValue(value: number, scale: Record<number, string>): string | null {\n if (Object.prototype.hasOwnProperty.call(scale, value)) {\n return scale[value]\n }\n return null\n}\n\nfunction normalizeTailwindArbitraryValue(value: string): string {\n return value.trim().replace(/\\s+/g, '_')\n}\n\nfunction normalizeShadowForComparison(value: string): string {\n return value\n .trim()\n .toLowerCase()\n .replace(/\\s*\\/\\s*/g, '/')\n .replace(/\\(\\s+/g, '(')\n .replace(/\\s+\\)/g, ')')\n .replace(/\\s*,\\s*/g, ',')\n .replace(/\\s+/g, ' ')\n}\n\nconst tailwindShadowClassValues: Array<{ className: string; css: string }> = [\n { className: 'shadow-2xs', css: '0 1px rgb(0 0 0 / 0.05)' },\n { className: 'shadow-xs', css: '0 1px 2px 0 rgb(0 0 0 / 0.05)' },\n { className: 'shadow', css: '0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)' },\n { className: 'shadow-sm', css: '0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)' },\n { className: 'shadow-md', css: '0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)' },\n { className: 'shadow-lg', css: '0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)' },\n { className: 'shadow-xl', css: '0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)' },\n { className: 'shadow-2xl', css: '0 25px 50px -12px rgb(0 0 0 / 0.25)' },\n { className: 'shadow-inner', css: 'inset 0 2px 4px 0 rgb(0 0 0 / 0.05)' },\n]\n\nexport function stylesToTailwind(styles: Record<string, string>): string {\n const classes: string[] = []\n\n for (const [prop, value] of Object.entries(styles)) {\n if (tailwindClassMap[prop]) {\n const parsed = parsePropertyValue(value)\n const mapping = tailwindClassMap[prop]\n if (value === 'auto') {\n classes.push(`${mapping.prefix}-auto`)\n continue\n }\n if (parsed.unit === 'px') {\n const exactScale = getExactScaleValue(parsed.numericValue, mapping.scale)\n if (exactScale !== null) {\n if (exactScale === '') {\n classes.push(mapping.prefix)\n } else {\n classes.push(`${mapping.prefix}-${exactScale}`)\n }\n continue\n }\n }\n classes.push(`${mapping.prefix}-[${value}]`)\n continue\n }\n\n if (prop === 'flex-direction' && flexDirectionMap[value]) {\n classes.push(flexDirectionMap[value])\n continue\n }\n\n if (prop === 'justify-content' && justifyContentMap[value]) {\n classes.push(justifyContentMap[value])\n continue\n }\n\n if (prop === 'align-items' && alignItemsMap[value]) {\n classes.push(alignItemsMap[value])\n continue\n }\n\n if (prop === 'display') {\n if (value === 'flex') classes.push('flex')\n else if (value === 'inline-flex') classes.push('inline-flex')\n else if (value === 'grid') classes.push('grid')\n else if (value === 'block') classes.push('block')\n else if (value === 'inline-block') classes.push('inline-block')\n else if (value === 'none') classes.push('hidden')\n continue\n }\n\n if (prop === 'width') {\n if (value === '100%') classes.push('w-full')\n else if (value === 'fit-content') classes.push('w-fit')\n else if (value === 'auto') classes.push('w-auto')\n else classes.push(`w-[${value}]`)\n continue\n }\n\n if (prop === 'height') {\n if (value === '100%') classes.push('h-full')\n else if (value === 'fit-content') classes.push('h-fit')\n else if (value === 'auto') classes.push('h-auto')\n else classes.push(`h-[${value}]`)\n continue\n }\n\n if (prop === 'background-color') {\n const colorValue = parseColorValue(value)\n classes.push(colorToTailwind('backgroundColor', colorValue))\n continue\n }\n\n if (prop === 'color') {\n const colorValue = parseColorValue(value)\n classes.push(colorToTailwind('color', colorValue))\n continue\n }\n\n if (prop === 'border-color') {\n const colorValue = parseColorValue(value)\n classes.push(colorToTailwind('borderColor', colorValue))\n continue\n }\n\n if (prop === 'border-style') {\n const styleMap: Record<string, string> = {\n none: 'border-none',\n solid: 'border-solid',\n dashed: 'border-dashed',\n dotted: 'border-dotted',\n double: 'border-double',\n }\n classes.push(styleMap[value] || `[border-style:${value}]`)\n continue\n }\n\n // Tailwind has no per-side border-style utilities — consolidate when all sides match\n if (prop === 'border-top-style' || prop === 'border-right-style' || prop === 'border-bottom-style' || prop === 'border-left-style') {\n const allPresent =\n 'border-top-style' in styles &&\n 'border-right-style' in styles &&\n 'border-bottom-style' in styles &&\n 'border-left-style' in styles\n if (allPresent) {\n // Only emit once (from border-top-style) when all four sides are present\n if (prop === 'border-top-style') {\n const allSame =\n styles['border-top-style'] === styles['border-right-style'] &&\n styles['border-top-style'] === styles['border-bottom-style'] &&\n styles['border-top-style'] === styles['border-left-style']\n if (allSame) {\n const styleMap: Record<string, string> = {\n none: 'border-none',\n solid: 'border-solid',\n dashed: 'border-dashed',\n dotted: 'border-dotted',\n double: 'border-double',\n }\n classes.push(styleMap[value] || `[border-style:${value}]`)\n } else {\n // Sides differ — emit each side individually\n classes.push(`[border-top-style:${styles['border-top-style']}]`)\n classes.push(`[border-right-style:${styles['border-right-style']}]`)\n classes.push(`[border-bottom-style:${styles['border-bottom-style']}]`)\n classes.push(`[border-left-style:${styles['border-left-style']}]`)\n }\n }\n } else {\n // Emit arbitrary-property syntax for individual side styles\n classes.push(`[${prop}:${value}]`)\n }\n continue\n }\n\n if (prop === 'outline-color') {\n const colorValue = parseColorValue(value)\n classes.push(colorToTailwind('outlineColor', colorValue))\n continue\n }\n\n if (prop === 'box-shadow') {\n const trimmed = value.trim()\n if (trimmed === 'none' || trimmed === '') {\n classes.push('shadow-none')\n } else {\n const normalized = normalizeShadowForComparison(trimmed)\n const preset = tailwindShadowClassValues.find(\n (entry) => normalizeShadowForComparison(entry.css) === normalized\n )\n if (preset) classes.push(preset.className)\n else classes.push(`shadow-[${normalizeTailwindArbitraryValue(value)}]`)\n }\n continue\n }\n\n if (prop === 'font-size') {\n classes.push(`text-[${value}]`)\n continue\n }\n\n if (prop === 'font-weight') {\n const weightMap: Record<string, string> = {\n '100': 'font-thin',\n '200': 'font-extralight',\n '300': 'font-light',\n '400': 'font-normal',\n '500': 'font-medium',\n '600': 'font-semibold',\n '700': 'font-bold',\n '800': 'font-extrabold',\n '900': 'font-black',\n }\n classes.push(weightMap[value] || `font-[${value}]`)\n continue\n }\n\n if (prop === 'line-height') {\n classes.push(`leading-[${value}]`)\n continue\n }\n\n if (prop === 'letter-spacing') {\n classes.push(`tracking-[${value}]`)\n continue\n }\n\n if (prop === 'text-align') {\n const alignMap: Record<string, string> = {\n left: 'text-left',\n center: 'text-center',\n right: 'text-right',\n justify: 'text-justify',\n }\n if (alignMap[value]) classes.push(alignMap[value])\n continue\n }\n\n if (prop === 'font-family') {\n classes.push(`font-[${value.replace(/\\s+/g, '_')}]`)\n continue\n }\n }\n\n return classes.join(' ')\n}\n\nexport const propertyToCSSMap: Record<SpacingPropertyKey, string> = {\n paddingTop: 'padding-top',\n paddingRight: 'padding-right',\n paddingBottom: 'padding-bottom',\n paddingLeft: 'padding-left',\n marginTop: 'margin-top',\n marginRight: 'margin-right',\n marginBottom: 'margin-bottom',\n marginLeft: 'margin-left',\n gap: 'gap',\n}\n\nexport const borderRadiusPropertyToCSSMap: Record<BorderRadiusPropertyKey, string> = {\n borderTopLeftRadius: 'border-top-left-radius',\n borderTopRightRadius: 'border-top-right-radius',\n borderBottomRightRadius: 'border-bottom-right-radius',\n borderBottomLeftRadius: 'border-bottom-left-radius',\n}\n\nexport const borderPropertyToCSSMap: Record<BorderPropertyKey, string> = {\n borderTopStyle: 'border-top-style',\n borderTopWidth: 'border-top-width',\n borderRightStyle: 'border-right-style',\n borderRightWidth: 'border-right-width',\n borderBottomStyle: 'border-bottom-style',\n borderBottomWidth: 'border-bottom-width',\n borderLeftStyle: 'border-left-style',\n borderLeftWidth: 'border-left-width',\n}\n\nexport const flexPropertyToCSSMap: Record<FlexPropertyKey, string> = {\n display: 'display',\n flexDirection: 'flex-direction',\n justifyContent: 'justify-content',\n alignItems: 'align-items',\n}\n\nexport const sizingPropertyToCSSMap: Record<SizingPropertyKey, string> = {\n width: 'width',\n height: 'height',\n}\n\nexport const typographyPropertyToCSSMap: Record<TypographyPropertyKey, string> = {\n fontFamily: 'font-family',\n fontWeight: 'font-weight',\n fontSize: 'font-size',\n lineHeight: 'line-height',\n letterSpacing: 'letter-spacing',\n textAlign: 'text-align',\n textVerticalAlign: 'align-items',\n}\n\nconst TEXT_ELEMENT_TAGS = new Set([\n 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',\n 'span', 'label', 'a', 'strong', 'em', 'small',\n 'blockquote', 'li', 'td', 'th', 'caption', 'figcaption',\n 'legend', 'dt', 'dd', 'abbr', 'cite', 'code', 'pre',\n])\n\nfunction hasDirectNonWhitespaceText(element: HTMLElement): boolean {\n return Array.from(element.childNodes).some(\n (node) => node.nodeType === Node.TEXT_NODE && Boolean(node.textContent?.trim())\n )\n}\n\nexport function isTextElement(element: HTMLElement): boolean {\n const tagName = element.tagName.toLowerCase()\n if (TEXT_ELEMENT_TAGS.has(tagName)) {\n return true\n }\n if (hasDirectNonWhitespaceText(element)) {\n return true\n }\n if (element.children.length === 0 && element.textContent?.trim()) {\n return true\n }\n return false\n}\n\nexport function getComputedTypography(element: HTMLElement): TypographyProperties {\n const computed = window.getComputedStyle(element)\n\n let textVerticalAlign: TypographyProperties['textVerticalAlign'] = 'flex-start'\n if (computed.display === 'flex' || computed.display === 'inline-flex') {\n const alignItems = computed.alignItems\n if (alignItems === 'center') textVerticalAlign = 'center'\n else if (alignItems === 'flex-end' || alignItems === 'end') textVerticalAlign = 'flex-end'\n }\n\n // Handle \"normal\" keyword for line-height (use font-size as approximation)\n const lineHeight = computed.lineHeight === 'normal'\n ? { numericValue: parseFloat(computed.fontSize) * 1.2, unit: 'px' as const, raw: `${Math.round(parseFloat(computed.fontSize) * 1.2)}px` }\n : parsePropertyValue(computed.lineHeight)\n\n // Handle letter-spacing: convert px to em for consistent editing\n const fontSize = parseFloat(computed.fontSize)\n let letterSpacing: CSSPropertyValue\n if (computed.letterSpacing === 'normal') {\n letterSpacing = { numericValue: 0, unit: 'em' as const, raw: '0em' }\n } else {\n const parsed = parsePropertyValue(computed.letterSpacing)\n if (parsed.unit === 'px' && fontSize > 0) {\n const emValue = Math.round((parsed.numericValue / fontSize) * 100) / 100\n letterSpacing = { numericValue: emValue, unit: 'em' as const, raw: `${emValue}em` }\n } else {\n letterSpacing = parsed\n }\n }\n\n return {\n fontFamily: computed.fontFamily,\n fontWeight: computed.fontWeight,\n fontSize: parsePropertyValue(computed.fontSize),\n lineHeight,\n letterSpacing,\n textAlign: computed.textAlign as TypographyProperties['textAlign'],\n textVerticalAlign,\n }\n}\n\nexport function detectSizingMode(\n element: HTMLElement,\n dimension: 'width' | 'height'\n): SizingMode {\n const computed = window.getComputedStyle(element)\n const inlineValue = element.style[dimension]\n\n if (inlineValue === '100%') return 'fill'\n if (inlineValue === 'auto' || inlineValue === 'fit-content') return 'fit'\n\n const computedValue = computed[dimension]\n\n if (computedValue === '100%') return 'fill'\n if (\n computedValue === 'auto' ||\n computedValue === 'fit-content' ||\n computedValue === 'max-content'\n ) {\n return 'fit'\n }\n\n const parent = element.parentElement\n if (parent) {\n const parentComputed = window.getComputedStyle(parent)\n if (parentComputed.display === 'flex' || parentComputed.display === 'inline-flex') {\n const flexGrow = computed.flexGrow\n if (flexGrow !== '0') {\n return 'fill'\n }\n }\n }\n\n if (dimension === 'width') {\n if (computed.display === 'block' && !inlineValue) {\n return 'fill'\n }\n if (\n computed.display === 'inline-block' ||\n computed.display === 'inline-flex' ||\n computed.display === 'inline'\n ) {\n return 'fit'\n }\n }\n\n if (dimension === 'height') {\n if (!inlineValue) {\n return 'fit'\n }\n }\n\n return 'fixed'\n}\n\nexport function getSizingValue(element: HTMLElement, dimension: 'width' | 'height'): SizingValue {\n const mode = detectSizingMode(element, dimension)\n const numericValue = Math.round(dimension === 'width' ? element.offsetWidth : element.offsetHeight)\n\n return {\n mode,\n value: {\n numericValue,\n unit: 'px',\n raw: `${numericValue}px`,\n },\n }\n}\n\nexport function getComputedSizing(element: HTMLElement): SizingProperties {\n return {\n width: getSizingValue(element, 'width'),\n height: getSizingValue(element, 'height'),\n }\n}\n\nexport function sizingValueToCSS(sizing: SizingValue): string {\n switch (sizing.mode) {\n case 'fill':\n return '100%'\n case 'fit':\n return 'fit-content'\n case 'fixed':\n return `${sizing.value.numericValue}${sizing.value.unit}`\n }\n}\n\nexport function sizingToTailwind(dimension: 'width' | 'height', sizing: SizingValue): string {\n const prefix = dimension === 'width' ? 'w' : 'h'\n\n switch (sizing.mode) {\n case 'fill':\n return `${prefix}-full`\n case 'fit':\n return `${prefix}-fit`\n case 'fixed':\n return `${prefix}-[${sizing.value.numericValue}${sizing.value.unit}]`\n }\n}\n\nfunction parseHexColor(hex: string): ColorValue {\n const raw = hex\n let h = hex.replace('#', '')\n\n // Expand shorthand (#RGB -> #RRGGBB)\n if (h.length === 3) {\n h = h\n .split('')\n .map((c) => c + c)\n .join('')\n }\n\n // Handle 8-digit hex with alpha\n if (h.length === 8) {\n const alpha = Math.round((parseInt(h.slice(6, 8), 16) / 255) * 100)\n return { hex: h.slice(0, 6).toUpperCase(), alpha, raw }\n }\n\n return { hex: h.toUpperCase(), alpha: 100, raw }\n}\n\nfunction parseRgbChannel(value: string): number | null {\n const token = value.trim()\n if (!token) return null\n\n if (token.endsWith('%')) {\n const numeric = parseFloat(token.slice(0, -1))\n if (!Number.isFinite(numeric)) return null\n return Math.round((Math.max(0, Math.min(100, numeric)) / 100) * 255)\n }\n\n const numeric = parseFloat(token)\n if (!Number.isFinite(numeric)) return null\n return Math.round(Math.max(0, Math.min(255, numeric)))\n}\n\nfunction parseRgbAlpha(value: string | undefined): number | null {\n if (value == null || value.trim() === '') return 1\n const token = value.trim()\n\n if (token.endsWith('%')) {\n const numeric = parseFloat(token.slice(0, -1))\n if (!Number.isFinite(numeric)) return null\n return Math.max(0, Math.min(100, numeric)) / 100\n }\n\n const numeric = parseFloat(token)\n if (!Number.isFinite(numeric)) return null\n return Math.max(0, Math.min(1, numeric))\n}\n\nfunction parseRgbaColor(rgba: string): ColorValue {\n const raw = rgba.trim()\n const fnMatch = raw.match(/^rgba?\\((.*)\\)$/i)\n if (!fnMatch) {\n return { hex: '000000', alpha: 100, raw: rgba }\n }\n\n const body = fnMatch[1].trim()\n let channelTokens: [string, string, string] | null = null\n let alphaToken: string | undefined\n\n const commaParts = body.split(',').map((part) => part.trim()).filter(Boolean)\n if (commaParts.length === 3 || commaParts.length === 4) {\n channelTokens = [commaParts[0], commaParts[1], commaParts[2]]\n alphaToken = commaParts[3]\n } else {\n const slashParts = body.split('/')\n if (slashParts.length === 1 || slashParts.length === 2) {\n const channels = slashParts[0].trim().split(/\\s+/).filter(Boolean)\n if (channels.length === 3) {\n channelTokens = [channels[0], channels[1], channels[2]]\n alphaToken = slashParts[1]?.trim()\n }\n }\n }\n\n if (!channelTokens) {\n return { hex: '000000', alpha: 100, raw: rgba }\n }\n\n const r = parseRgbChannel(channelTokens[0])\n const g = parseRgbChannel(channelTokens[1])\n const b = parseRgbChannel(channelTokens[2])\n const a = parseRgbAlpha(alphaToken)\n\n if (r === null || g === null || b === null || a === null) {\n return { hex: '000000', alpha: 100, raw: rgba }\n }\n\n const hex = [r, g, b]\n .map((v) => v.toString(16).padStart(2, '0'))\n .join('')\n .toUpperCase()\n const alpha = Math.round(a * 100)\n\n return { hex, alpha, raw: rgba }\n}\n\nfunction parseNamedColor(name: string): ColorValue {\n // Use a temporary canvas to convert named colors\n const ctx = document.createElement('canvas').getContext('2d')\n if (!ctx) {\n return { hex: '000000', alpha: 100, raw: name }\n }\n\n ctx.fillStyle = name\n const computed = ctx.fillStyle\n\n if (computed.startsWith('#')) {\n return parseHexColor(computed)\n }\n return parseRgbaColor(computed)\n}\n\nexport function parseColorValue(cssValue: string): ColorValue {\n const raw = cssValue.trim()\n\n // Handle transparent\n if (raw === 'transparent') {\n return { hex: '000000', alpha: 0, raw }\n }\n\n // Handle hex colors\n if (raw.startsWith('#')) {\n return parseHexColor(raw)\n }\n\n // Handle rgb/rgba\n if (raw.startsWith('rgb')) {\n return parseRgbaColor(raw)\n }\n\n // Fallback: use canvas to convert named colors\n return parseNamedColor(raw)\n}\n\nconst TRANSPARENT_COLOR: ColorValue = { hex: '000000', alpha: 0, raw: 'transparent' }\n\nfunction isVisibleBorderSide(side: { style: string; width: string }): boolean {\n return side.style !== 'none' && side.style !== 'hidden' && parseFloat(side.width) > 0\n}\n\nfunction hasVisibleOutline(computed: CSSStyleDeclaration): boolean {\n return computed.outlineStyle !== 'none' && parseFloat(computed.outlineWidth) > 0\n}\n\nfunction parseVisibleColor(\n value: string,\n fallbackCurrentColor?: string\n): ColorValue | null {\n const raw = value.trim()\n const lowered = raw.toLowerCase()\n if (!raw || lowered === 'none' || lowered === 'transparent') {\n return null\n }\n\n const resolved = /^currentcolor$/i.test(raw)\n ? (fallbackCurrentColor ?? raw)\n : raw\n const parsed = parseColorValue(resolved)\n if (parsed.alpha <= 0) {\n return null\n }\n return parsed\n}\n\nfunction addUniqueColor(\n colors: Map<string, ColorValue>,\n color: ColorValue | null\n): void {\n if (!color) return\n colors.set(`${color.hex}:${color.alpha}`, color)\n}\n\nfunction isTextRenderingFormControl(element: HTMLElement): boolean {\n if (element instanceof HTMLTextAreaElement) return true\n if (element instanceof HTMLSelectElement) return true\n if (element instanceof HTMLButtonElement) return true\n if (element instanceof HTMLInputElement) {\n const textlessInputTypes = new Set([\n 'hidden',\n 'checkbox',\n 'radio',\n 'range',\n 'color',\n 'file',\n 'image',\n ])\n return !textlessInputTypes.has(element.type.toLowerCase())\n }\n return false\n}\n\nfunction hasRenderableTextNode(element: HTMLElement): boolean {\n if (element.isContentEditable) return true\n if (isTextRenderingFormControl(element)) return true\n if (!element.textContent?.trim()) return false\n if (hasDirectNonWhitespaceText(element)) return true\n const tagName = element.tagName.toLowerCase()\n return TEXT_ELEMENT_TAGS.has(tagName) || element.children.length === 0\n}\n\nexport function getComputedBoxShadow(element: HTMLElement): string {\n const computed = window.getComputedStyle(element)\n const value = computed.boxShadow.trim()\n return value || 'none'\n}\n\nexport function getComputedColorStyles(element: HTMLElement): ColorProperties {\n const computed = window.getComputedStyle(element)\n\n const borderSides = [\n { style: computed.borderTopStyle, width: computed.borderTopWidth, color: computed.borderTopColor },\n { style: computed.borderRightStyle, width: computed.borderRightWidth, color: computed.borderRightColor },\n { style: computed.borderBottomStyle, width: computed.borderBottomWidth, color: computed.borderBottomColor },\n { style: computed.borderLeftStyle, width: computed.borderLeftWidth, color: computed.borderLeftColor },\n ]\n const visibleBorderSide = borderSides.find((side) => isVisibleBorderSide(side))\n const hasBorder = Boolean(visibleBorderSide)\n const hasOutline = hasVisibleOutline(computed)\n\n return {\n backgroundColor: parseColorValue(computed.backgroundColor),\n color: parseColorValue(computed.color),\n borderColor: hasBorder && visibleBorderSide ? parseColorValue(visibleBorderSide.color) : TRANSPARENT_COLOR,\n outlineColor: hasOutline ? parseColorValue(computed.outlineColor) : TRANSPARENT_COLOR,\n }\n}\n\nexport function getSelectionColors(element: HTMLElement): ColorValue[] {\n const uniqueColors = new Map<string, ColorValue>()\n const queue: Element[] = [element]\n\n for (let index = 0; index < queue.length; index++) {\n const node = queue[index]\n const computed = window.getComputedStyle(node)\n\n if (computed.display === 'none') {\n // Entire subtree is not rendered; skip traversal for performance.\n continue\n }\n\n const isVisibilityHidden =\n computed.visibility === 'hidden' || computed.visibility === 'collapse'\n const currentTextColor = computed.color\n\n if (!isVisibilityHidden) {\n addUniqueColor(uniqueColors, parseVisibleColor(computed.backgroundColor))\n\n if (node instanceof HTMLElement && hasRenderableTextNode(node)) {\n addUniqueColor(uniqueColors, parseVisibleColor(currentTextColor))\n }\n\n const borderSides = [\n { style: computed.borderTopStyle, width: computed.borderTopWidth, color: computed.borderTopColor },\n { style: computed.borderRightStyle, width: computed.borderRightWidth, color: computed.borderRightColor },\n { style: computed.borderBottomStyle, width: computed.borderBottomWidth, color: computed.borderBottomColor },\n { style: computed.borderLeftStyle, width: computed.borderLeftWidth, color: computed.borderLeftColor },\n ]\n for (const side of borderSides) {\n if (!isVisibleBorderSide(side)) continue\n addUniqueColor(uniqueColors, parseVisibleColor(side.color, currentTextColor))\n }\n\n if (hasVisibleOutline(computed)) {\n addUniqueColor(uniqueColors, parseVisibleColor(computed.outlineColor, currentTextColor))\n }\n\n if (node instanceof SVGElement) {\n const fillColor =\n parseVisibleColor(computed.getPropertyValue('fill'), currentTextColor)\n ?? parseVisibleColor(node.getAttribute('fill') ?? '', currentTextColor)\n const strokeColor =\n parseVisibleColor(computed.getPropertyValue('stroke'), currentTextColor)\n ?? parseVisibleColor(node.getAttribute('stroke') ?? '', currentTextColor)\n addUniqueColor(uniqueColors, fillColor)\n addUniqueColor(uniqueColors, strokeColor)\n }\n }\n\n for (const child of node.children) {\n queue.push(child)\n }\n }\n\n return Array.from(uniqueColors.values())\n}\n\nexport interface AllComputedStyles {\n spacing: SpacingProperties\n borderRadius: BorderRadiusProperties\n border: BorderProperties\n flex: FlexProperties\n sizing: SizingProperties\n color: ColorProperties\n boxShadow: string\n typography: TypographyProperties\n}\n\nexport function getAllComputedStyles(element: HTMLElement): AllComputedStyles {\n const { spacing, borderRadius, flex } = getComputedStyles(element)\n return {\n spacing,\n borderRadius,\n border: getComputedBorderStyles(element),\n flex,\n sizing: getComputedSizing(element),\n color: getComputedColorStyles(element),\n boxShadow: getComputedBoxShadow(element),\n typography: getComputedTypography(element),\n }\n}\n\nexport const colorPropertyToCSSMap: Record<ColorPropertyKey, string> = {\n backgroundColor: 'background-color',\n color: 'color',\n borderColor: 'border-color',\n outlineColor: 'outline-color',\n}\n\nconst colorTailwindPrefixMap: Record<ColorPropertyKey, string> = {\n backgroundColor: 'bg',\n color: 'text',\n borderColor: 'border',\n outlineColor: 'outline',\n}\n\nexport function colorToTailwind(\n property: ColorPropertyKey,\n colorValue: ColorValue\n): string {\n const prefix = colorTailwindPrefixMap[property]\n\n // Use arbitrary hex value\n if (colorValue.alpha === 100) {\n return `${prefix}-[#${colorValue.hex}]`\n }\n return `${prefix}-[#${colorValue.hex}]/${colorValue.alpha}`\n}\n\nexport function getElementInfo(element: HTMLElement): ElementInfo {\n const computed = window.getComputedStyle(element)\n const parentElement = element === document.body ? null : element.parentElement\n\n const isFlexContainer = computed.display === 'flex' || computed.display === 'inline-flex'\n\n let isFlexItem = false\n if (parentElement) {\n const parentComputed = window.getComputedStyle(parentElement)\n isFlexItem = parentComputed.display === 'flex' || parentComputed.display === 'inline-flex'\n }\n\n return {\n tagName: element.tagName.toLowerCase(),\n id: element.id || null,\n classList: Array.from(element.classList),\n isFlexContainer,\n isFlexItem,\n isTextElement: isTextElement(element),\n parentElement,\n hasChildren: element.children.length > 0,\n }\n}\n\ninterface DimensionDisplay {\n width: string\n height: string\n}\n\nfunction isFitSizing(element: HTMLElement, dimension: 'width' | 'height'): boolean {\n const computed = window.getComputedStyle(element)\n const inlineValue = element.style[dimension]\n\n if (inlineValue === 'auto') return true\n\n const computedValue = computed[dimension]\n\n if (!inlineValue) {\n const parent = element.parentElement\n if (parent) {\n const parentComputed = window.getComputedStyle(parent)\n if (parentComputed.display === 'flex' || parentComputed.display === 'inline-flex') {\n const flexBasis = computed.flexBasis\n const flexGrow = computed.flexGrow\n if (flexBasis === 'auto' && flexGrow === '0') {\n return true\n }\n }\n }\n\n if (dimension === 'width') {\n if (computed.display === 'block' && !inlineValue) {\n return false\n }\n if (\n computed.display === 'inline-block' ||\n computed.display === 'inline-flex' ||\n computed.display === 'inline'\n ) {\n return true\n }\n }\n\n if (dimension === 'height') {\n return !inlineValue\n }\n }\n\n if (computedValue.includes('fit-content') || computedValue.includes('max-content')) {\n return true\n }\n\n return false\n}\n\nexport function getDimensionDisplay(element: HTMLElement): DimensionDisplay {\n const width = Math.round(element.offsetWidth)\n const height = Math.round(element.offsetHeight)\n\n const widthIsFit = isFitSizing(element, 'width')\n const heightIsFit = isFitSizing(element, 'height')\n\n return {\n width: widthIsFit ? `Fit ${width}` : `${width}`,\n height: heightIsFit ? `Fit ${height}` : `${height}`,\n }\n}\n\n\nexport function calculateParentMeasurements(element: HTMLElement, container?: HTMLElement): MeasurementLine[] {\n const parent = container ?? element.parentElement\n if (!parent) return []\n\n const elementRect = element.getBoundingClientRect()\n const parentRect = parent.getBoundingClientRect()\n\n // Use clientLeft/clientTop for reliable border widths, clientWidth/clientHeight\n // for inner dimensions (handles scrollbars correctly)\n const paddingBoxLeft = parentRect.left + parent.clientLeft\n const paddingBoxTop = parentRect.top + parent.clientTop\n const paddingBoxRight = parentRect.left + parent.clientLeft + parent.clientWidth\n const paddingBoxBottom = parentRect.top + parent.clientTop + parent.clientHeight\n\n let parentInnerLeft: number\n let parentInnerTop: number\n let parentInnerRight: number\n let parentInnerBottom: number\n\n if (container) {\n // Ancestor case: measure from padding-box (inside border, outside padding).\n // The ancestor's padding doesn't directly position the child — intermediate\n // elements do — so the visually correct edge is inside the border only.\n parentInnerLeft = paddingBoxLeft\n parentInnerTop = paddingBoxTop\n parentInnerRight = paddingBoxRight\n parentInnerBottom = paddingBoxBottom\n } else {\n // Direct parent case: measure from content-box (inside border and padding).\n // The parent's padding IS the gap between its edge and the child's layout area.\n const parentStyles = window.getComputedStyle(parent)\n parentInnerLeft = paddingBoxLeft + (parseFloat(parentStyles.paddingLeft) || 0)\n parentInnerTop = paddingBoxTop + (parseFloat(parentStyles.paddingTop) || 0)\n parentInnerRight = paddingBoxRight - (parseFloat(parentStyles.paddingRight) || 0)\n parentInnerBottom = paddingBoxBottom - (parseFloat(parentStyles.paddingBottom) || 0)\n }\n\n const zoom = getZoomScale()\n const measurements: MeasurementLine[] = []\n\n const topDistance = Math.round((elementRect.top - parentInnerTop) / zoom)\n if (topDistance > 0) {\n const midX = elementRect.left + elementRect.width / 2\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: parentInnerTop,\n x2: midX,\n y2: elementRect.top,\n distance: topDistance,\n labelPosition: { x: midX, y: (parentInnerTop + elementRect.top) / 2 },\n })\n }\n\n const bottomDistance = Math.round((parentInnerBottom - elementRect.bottom) / zoom)\n if (bottomDistance > 0) {\n const midX = elementRect.left + elementRect.width / 2\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: elementRect.bottom,\n x2: midX,\n y2: parentInnerBottom,\n distance: bottomDistance,\n labelPosition: { x: midX, y: (elementRect.bottom + parentInnerBottom) / 2 },\n })\n }\n\n const leftDistance = Math.round((elementRect.left - parentInnerLeft) / zoom)\n if (leftDistance > 0) {\n const midY = elementRect.top + elementRect.height / 2\n measurements.push({\n direction: 'horizontal',\n x1: parentInnerLeft,\n y1: midY,\n x2: elementRect.left,\n y2: midY,\n distance: leftDistance,\n labelPosition: { x: (parentInnerLeft + elementRect.left) / 2, y: midY },\n })\n }\n\n const rightDistance = Math.round((parentInnerRight - elementRect.right) / zoom)\n if (rightDistance > 0) {\n const midY = elementRect.top + elementRect.height / 2\n measurements.push({\n direction: 'horizontal',\n x1: elementRect.right,\n y1: midY,\n x2: parentInnerRight,\n y2: midY,\n distance: rightDistance,\n labelPosition: { x: (elementRect.right + parentInnerRight) / 2, y: midY },\n })\n }\n\n return measurements\n}\n\nexport function calculateElementMeasurements(\n from: HTMLElement,\n to: HTMLElement\n): MeasurementLine[] {\n const fromRect = from.getBoundingClientRect()\n const toRect = to.getBoundingClientRect()\n const zoom = getZoomScale()\n const measurements: MeasurementLine[] = []\n\n const horizontalOverlap =\n fromRect.left < toRect.right && fromRect.right > toRect.left\n const verticalOverlap =\n fromRect.top < toRect.bottom && fromRect.bottom > toRect.top\n\n if (verticalOverlap) {\n const overlapTop = Math.max(fromRect.top, toRect.top)\n const overlapBottom = Math.min(fromRect.bottom, toRect.bottom)\n const midY = (overlapTop + overlapBottom) / 2\n\n if (fromRect.right <= toRect.left) {\n const distance = Math.round((toRect.left - fromRect.right) / zoom)\n measurements.push({\n direction: 'horizontal',\n x1: fromRect.right,\n y1: midY,\n x2: toRect.left,\n y2: midY,\n distance,\n labelPosition: { x: (fromRect.right + toRect.left) / 2, y: midY },\n })\n } else if (fromRect.left >= toRect.right) {\n const distance = Math.round((fromRect.left - toRect.right) / zoom)\n measurements.push({\n direction: 'horizontal',\n x1: toRect.right,\n y1: midY,\n x2: fromRect.left,\n y2: midY,\n distance,\n labelPosition: { x: (toRect.right + fromRect.left) / 2, y: midY },\n })\n }\n }\n\n if (horizontalOverlap) {\n const overlapLeft = Math.max(fromRect.left, toRect.left)\n const overlapRight = Math.min(fromRect.right, toRect.right)\n const midX = (overlapLeft + overlapRight) / 2\n\n if (fromRect.bottom <= toRect.top) {\n const distance = Math.round((toRect.top - fromRect.bottom) / zoom)\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: fromRect.bottom,\n x2: midX,\n y2: toRect.top,\n distance,\n labelPosition: { x: midX, y: (fromRect.bottom + toRect.top) / 2 },\n })\n } else if (fromRect.top >= toRect.bottom) {\n const distance = Math.round((fromRect.top - toRect.bottom) / zoom)\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: toRect.bottom,\n x2: midX,\n y2: fromRect.top,\n distance,\n labelPosition: { x: midX, y: (toRect.bottom + fromRect.top) / 2 },\n })\n }\n }\n\n if (!horizontalOverlap && !verticalOverlap) {\n const fromCenterX = fromRect.left + fromRect.width / 2\n const fromCenterY = fromRect.top + fromRect.height / 2\n const toCenterX = toRect.left + toRect.width / 2\n const toCenterY = toRect.top + toRect.height / 2\n\n const hDistance = toCenterX > fromCenterX\n ? Math.round((toRect.left - fromRect.right) / zoom)\n : Math.round((fromRect.left - toRect.right) / zoom)\n\n if (hDistance > 0) {\n const startX = toCenterX > fromCenterX ? fromRect.right : fromRect.left\n const endX = toCenterX > fromCenterX ? toRect.left : toRect.right\n const y = (fromCenterY + toCenterY) / 2\n measurements.push({\n direction: 'horizontal',\n x1: startX,\n y1: y,\n x2: endX,\n y2: y,\n distance: hDistance,\n labelPosition: { x: (startX + endX) / 2, y },\n })\n }\n\n const vDistance = toCenterY > fromCenterY\n ? Math.round((toRect.top - fromRect.bottom) / zoom)\n : Math.round((fromRect.top - toRect.bottom) / zoom)\n\n if (vDistance > 0) {\n const x = (fromCenterX + toCenterX) / 2\n const startY = toCenterY > fromCenterY ? fromRect.bottom : fromRect.top\n const endY = toCenterY > fromCenterY ? toRect.top : toRect.bottom\n measurements.push({\n direction: 'vertical',\n x1: x,\n y1: startY,\n x2: x,\n y2: endY,\n distance: vDistance,\n labelPosition: { x, y: (startY + endY) / 2 },\n })\n }\n }\n\n return measurements\n}\n\nconst GUIDELINE_PROXIMITY = 80\n\nexport function calculateGuidelineMeasurements(\n element: HTMLElement,\n guidelines: Guideline[],\n mousePosition?: { x: number; y: number } | null,\n): MeasurementLine[] {\n if (guidelines.length === 0) return []\n\n const snap = getCanvasSnapshot()\n const zoom = snap.active ? snap.zoom : 1\n const rect = element.getBoundingClientRect()\n const measurements: MeasurementLine[] = []\n\n for (const g of guidelines) {\n let viewportPos: number\n if (snap.active) {\n const pan = g.orientation === 'horizontal' ? snap.panY : snap.panX\n const bo = g.orientation === 'horizontal' ? getBodyOffset().y : getBodyOffset().x\n viewportPos = bo + (g.position - bo + pan) * zoom\n } else {\n const scroll = g.orientation === 'horizontal' ? window.scrollY : window.scrollX\n viewportPos = g.position - scroll\n }\n\n if (g.orientation === 'horizontal') {\n const midX = rect.left + rect.width / 2\n\n if (mousePosition && Math.abs(mousePosition.y - viewportPos) > GUIDELINE_PROXIMITY) continue\n\n if (viewportPos < rect.top) {\n const distance = Math.round((rect.top - viewportPos) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: viewportPos,\n x2: midX,\n y2: rect.top,\n distance,\n labelPosition: { x: midX, y: (viewportPos + rect.top) / 2 },\n })\n }\n } else if (viewportPos > rect.bottom) {\n const distance = Math.round((viewportPos - rect.bottom) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: rect.bottom,\n x2: midX,\n y2: viewportPos,\n distance,\n labelPosition: { x: midX, y: (rect.bottom + viewportPos) / 2 },\n })\n }\n }\n } else {\n const midY = rect.top + rect.height / 2\n\n if (mousePosition && Math.abs(mousePosition.x - viewportPos) > GUIDELINE_PROXIMITY) continue\n\n if (viewportPos < rect.left) {\n const distance = Math.round((rect.left - viewportPos) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'horizontal',\n x1: viewportPos,\n y1: midY,\n x2: rect.left,\n y2: midY,\n distance,\n labelPosition: { x: (viewportPos + rect.left) / 2, y: midY },\n })\n }\n } else if (viewportPos > rect.right) {\n const distance = Math.round((viewportPos - rect.right) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'horizontal',\n x1: rect.right,\n y1: midY,\n x2: viewportPos,\n y2: midY,\n distance,\n labelPosition: { x: (rect.right + viewportPos) / 2, y: midY },\n })\n }\n }\n }\n }\n\n return measurements\n}\n\nexport function isFlexContainer(element: HTMLElement): boolean {\n const computed = window.getComputedStyle(element)\n return computed.display === 'flex' || computed.display === 'inline-flex'\n}\n\nexport function getFlexDirection(\n element: HTMLElement\n): 'row' | 'row-reverse' | 'column' | 'column-reverse' {\n const computed = window.getComputedStyle(element)\n return computed.flexDirection as 'row' | 'row-reverse' | 'column' | 'column-reverse'\n}\n\n/** True when the child participates in normal flow (not hidden, absolute, or fixed). */\nexport function isInFlowChild(el: HTMLElement): boolean {\n const cs = window.getComputedStyle(el)\n return cs.display !== 'none' && cs.position !== 'absolute' && cs.position !== 'fixed'\n}\n\nexport function detectChildrenDirection(\n container: HTMLElement,\n exclude: HTMLElement | null\n): { axis: 'horizontal' | 'vertical'; reversed: boolean } {\n const computed = window.getComputedStyle(container)\n\n // Flex: trust CSS for accuracy (especially reverse)\n if (computed.display === 'flex' || computed.display === 'inline-flex') {\n const dir = computed.flexDirection\n return {\n axis: (dir === 'row' || dir === 'row-reverse') ? 'horizontal' : 'vertical',\n reversed: dir === 'row-reverse' || dir === 'column-reverse',\n }\n }\n\n // Non-flex: examine first two visible, in-flow children\n const visible: HTMLElement[] = []\n for (const c of container.children) {\n if (!(c instanceof HTMLElement) || c === exclude) continue\n if (!isInFlowChild(c)) continue\n visible.push(c)\n if (visible.length === 2) break\n }\n\n if (visible.length < 2) return { axis: 'vertical', reversed: false }\n\n const first = visible[0].getBoundingClientRect()\n const second = visible[1].getBoundingClientRect()\n const yOverlap = first.bottom - 2 > second.top && second.bottom - 2 > first.top\n\n if (yOverlap) {\n return { axis: 'horizontal', reversed: second.right < first.left }\n }\n return { axis: 'vertical', reversed: second.bottom < first.top }\n}\n\nexport function computeIntendedIndex(\n parent: HTMLElement,\n draggedElement: HTMLElement,\n): {\n index: number\n siblingBefore: HTMLElement | null\n siblingAfter: HTMLElement | null\n} {\n const { axis } = detectChildrenDirection(parent, draggedElement)\n const isHorizontal = axis === 'horizontal'\n const draggedRect = draggedElement.getBoundingClientRect()\n const intendedCenter = isHorizontal\n ? draggedRect.left + draggedRect.width / 2\n : draggedRect.top + draggedRect.height / 2\n\n const siblings: HTMLElement[] = []\n for (const c of parent.children) {\n if (!(c instanceof HTMLElement) || c === draggedElement) continue\n if (!isInFlowChild(c)) continue\n siblings.push(c)\n }\n\n if (siblings.length === 0) {\n return { index: 0, siblingBefore: null, siblingAfter: null }\n }\n\n for (let i = 0; i < siblings.length; i++) {\n const rect = siblings[i].getBoundingClientRect()\n const midpoint = isHorizontal\n ? rect.left + rect.width / 2\n : rect.top + rect.height / 2\n if (intendedCenter < midpoint) {\n return { index: i, siblingBefore: i > 0 ? siblings[i - 1] : null, siblingAfter: siblings[i] }\n }\n }\n\n return { index: siblings.length, siblingBefore: siblings[siblings.length - 1], siblingAfter: null }\n}\n\nfunction htmlChildren(el: HTMLElement): HTMLElement[] {\n return Array.from(el.children).filter(\n (child): child is HTMLElement => child instanceof HTMLElement\n )\n}\n\n/** Walk up from `element` to find the nearest flex/inline-flex ancestor, stopping at `boundary`. */\nfunction findFlexAncestor(\n element: HTMLElement,\n boundary: HTMLElement | null,\n): { flexParent: HTMLElement; child: HTMLElement } | null {\n let current: HTMLElement | null = element\n while (current && current !== document.body) {\n const parent: HTMLElement | null = current.parentElement\n if (!parent) break\n const display = getComputedStyle(parent).display\n if (display === 'flex' || display === 'inline-flex') {\n return { flexParent: parent, child: current }\n }\n if (boundary && parent === boundary) break\n current = parent\n }\n return null\n}\n\nexport function computeHoverHighlight(\n elementUnder: HTMLElement | null,\n selectedElement: HTMLElement | null,\n): { flexContainer: HTMLElement; children: HTMLElement[] } | null {\n if (\n !elementUnder ||\n elementUnder === document.body ||\n elementUnder === document.documentElement ||\n elementUnder.closest('[data-direct-edit]') ||\n elementUnder.closest('[data-direct-edit-host]') ||\n elementUnder === selectedElement\n ) {\n return null\n }\n\n // When hovering descendants of the selected element, stop walk-up at the boundary\n const boundary = selectedElement?.contains(elementUnder) ? selectedElement : null\n\n const ownDisplay = getComputedStyle(elementUnder).display\n if (ownDisplay === 'flex' || ownDisplay === 'inline-flex') {\n return { flexContainer: elementUnder, children: htmlChildren(elementUnder) }\n }\n\n const found = findFlexAncestor(elementUnder, boundary)\n if (found) {\n return { flexContainer: found.flexParent, children: htmlChildren(found.flexParent) }\n }\n\n return { flexContainer: elementUnder, children: [] }\n}\n\nexport function resolveElementTarget(\n elementUnder: HTMLElement,\n selectedElement: HTMLElement | null,\n): HTMLElement {\n const boundary = selectedElement?.contains(elementUnder) ? selectedElement : null\n const found = findFlexAncestor(elementUnder, boundary)\n if (found && found.flexParent === boundary) return elementUnder\n return found?.child ?? elementUnder\n}\n\n/** Finds the text-owning element at a point within `boundary` using browser caret hit-testing. */\nexport function findTextOwnerAtPoint(\n boundary: HTMLElement,\n clientX: number,\n clientY: number,\n): HTMLElement | null {\n const doc = document as Document & {\n caretPositionFromPoint?: (x: number, y: number) => { offsetNode: Node } | null\n caretRangeFromPoint?: (x: number, y: number) => Range | null\n }\n\n const caretNode =\n doc.caretPositionFromPoint?.(clientX, clientY)?.offsetNode\n ?? doc.caretRangeFromPoint?.(clientX, clientY)?.startContainer\n ?? null\n if (!caretNode || caretNode.nodeType !== Node.TEXT_NODE) return null\n\n const textNode = caretNode as Text\n if (!(textNode.nodeValue ?? '').trim()) return null\n\n const owner = textNode.parentElement\n if (!owner || !boundary.contains(owner)) return null\n if (owner.closest('[data-direct-edit]') || owner.closest('[data-direct-edit-host]')) return null\n\n // Guard against caret APIs returning nearby text nodes.\n const range = document.createRange()\n range.selectNodeContents(textNode)\n const hitsText = Array.from(range.getClientRects()).some(\n (r) => clientX >= r.left && clientX <= r.right && clientY >= r.top && clientY <= r.bottom\n )\n range.detach?.()\n return hitsText ? owner : null\n}\n\n/** Fallback text hit-testing by scanning text nodes and rendered rects within `boundary`. */\nexport function findTextOwnerByRangeScan(\n boundary: HTMLElement,\n clientX: number,\n clientY: number,\n): HTMLElement | null {\n const walker = document.createTreeWalker(boundary, NodeFilter.SHOW_TEXT)\n let current: Node | null = walker.nextNode()\n\n while (current) {\n const textNode = current as Text\n if ((textNode.nodeValue ?? '').trim()) {\n const owner = textNode.parentElement\n if (\n owner &&\n boundary.contains(owner) &&\n !owner.closest('[data-direct-edit]') &&\n !owner.closest('[data-direct-edit-host]')\n ) {\n const range = document.createRange()\n range.selectNodeContents(textNode)\n const hitsText = Array.from(range.getClientRects()).some(\n (r) => clientX >= r.left && clientX <= r.right && clientY >= r.top && clientY <= r.bottom\n )\n range.detach?.()\n if (hitsText) return owner\n }\n }\n current = walker.nextNode()\n }\n\n return null\n}\n\n/** Wrap the direct text node under the point into a span so it becomes independently selectable. */\nexport function ensureDirectTextSpanAtPoint(\n parent: HTMLElement,\n clientX: number,\n clientY: number,\n): HTMLElement | null {\n const directTextNodes = Array.from(parent.childNodes).filter(\n (node): node is Text => node.nodeType === Node.TEXT_NODE && Boolean(node.textContent?.trim())\n )\n\n for (const textNode of directTextNodes) {\n const range = document.createRange()\n range.selectNodeContents(textNode)\n const hitsText = Array.from(range.getClientRects()).some(\n (r) => clientX >= r.left && clientX <= r.right && clientY >= r.top && clientY <= r.bottom\n )\n range.detach?.()\n\n if (!hitsText) continue\n\n const span = document.createElement('span')\n span.setAttribute('data-direct-edit-generated', 'text-span')\n span.textContent = textNode.textContent ?? ''\n parent.replaceChild(span, textNode)\n return span\n }\n\n return null\n}\n\n/** When elementFromPoint returns the selected element (bare text, padding, gap),\n * find the best child element to drill into at the given coordinates. */\nexport function findChildAtPoint(\n parent: HTMLElement,\n clientX: number,\n clientY: number,\n): HTMLElement | null {\n const children = htmlChildren(parent)\n if (children.length === 0) return null\n\n // Direct hit: child whose bbox contains the click\n const hit = children.find((child) => {\n const r = child.getBoundingClientRect()\n return clientX >= r.left && clientX <= r.right && clientY >= r.top && clientY <= r.bottom\n })\n if (hit) return hit\n\n // Single-child fallback should not steal clicks from parent's direct text.\n if (children.length === 1 && !hasDirectNonWhitespaceText(parent)) return children[0]\n\n return null\n}\n\nexport function elementFromPointWithoutOverlays(x: number, y: number): HTMLElement | null {\n const host = document.querySelector<HTMLElement>('[data-direct-edit-host]')\n if (host) host.style.display = 'none'\n const el = document.elementFromPoint(x, y) as HTMLElement | null\n if (host) host.style.display = ''\n return el\n}\n\nexport function isLayoutContainer(element: HTMLElement): boolean {\n const display = window.getComputedStyle(element).display\n return (\n display === 'flex' ||\n display === 'inline-flex' ||\n display === 'grid' ||\n display === 'inline-grid'\n )\n}\n\nfunction isBlockContainer(element: HTMLElement): boolean {\n const display = window.getComputedStyle(element).display\n return display === 'block' || display === 'flow-root'\n || display === 'inline-block' || display === 'list-item'\n}\n\nfunction skipElement(el: HTMLElement, exclude: HTMLElement | null): boolean {\n if (exclude && exclude.contains(el)) return true\n if (el === document.body || el === document.documentElement) return true\n if (el.closest('[data-direct-edit]') || el.closest('[data-direct-edit-host]')) return true\n return false\n}\n\nfunction findContainerViaTraversal(x: number, y: number, exclude: HTMLElement | null): HTMLElement | null {\n const el = elementFromPointWithoutOverlays(x, y)\n if (!el) return null\n let current: HTMLElement | null = el\n while (current) {\n if (!skipElement(current, exclude)) {\n if (isLayoutContainer(current) || isBlockContainer(current)) return current\n }\n current = current.parentElement\n }\n return null\n}\n\nexport function findContainerAtPoint(\n x: number,\n y: number,\n exclude: HTMLElement | null,\n preferredParent?: HTMLElement | null\n): HTMLElement | null {\n const host = document.querySelector<HTMLElement>('[data-direct-edit-host]')\n if (host) host.style.display = 'none'\n\n const elements = document.elementsFromPoint(x, y) as HTMLElement[]\n\n if (host) host.style.display = ''\n\n // Find most specific container (front-to-back = most nested first)\n for (const el of elements) {\n if (skipElement(el, exclude)) continue\n if (isLayoutContainer(el) || isBlockContainer(el)) return el\n }\n\n // Fallback: preferredParent for gap/padding areas\n if (preferredParent && (isLayoutContainer(preferredParent) || isBlockContainer(preferredParent))) {\n for (const el of elements) {\n if (el === preferredParent) return preferredParent\n }\n }\n\n // Last resort: walk up DOM\n return findContainerViaTraversal(x, y, exclude)\n}\n\nexport function findLayoutContainerAtPoint(\n x: number,\n y: number,\n exclude: HTMLElement | null,\n preferredParent?: HTMLElement | null,\n): HTMLElement | null {\n const host = document.querySelector<HTMLElement>('[data-direct-edit-host]')\n if (host) host.style.display = 'none'\n const elements = document.elementsFromPoint(x, y) as HTMLElement[]\n if (host) host.style.display = ''\n\n for (const el of elements) {\n if (skipElement(el, exclude)) continue\n if (isLayoutContainer(el)) return el\n }\n\n if (preferredParent && isLayoutContainer(preferredParent)) {\n for (const el of elements) {\n if (el === preferredParent) return preferredParent\n }\n }\n\n return null\n}\n\nexport function calculateDropPosition(\n container: HTMLElement,\n pointerX: number,\n pointerY: number,\n draggedElement: HTMLElement\n): { insertBefore: HTMLElement | null; indicator: DropIndicator } | null {\n const { axis, reversed: isReversed } = detectChildrenDirection(container, draggedElement)\n const isHorizontal = axis === 'horizontal'\n\n const children = Array.from(container.children).filter(\n (child) => child !== draggedElement && child instanceof HTMLElement\n ) as HTMLElement[]\n\n if (children.length === 0) {\n const containerRect = container.getBoundingClientRect()\n return {\n insertBefore: null,\n indicator: {\n x: containerRect.left + 4,\n y: containerRect.top + 4,\n width: isHorizontal ? 1 : containerRect.width - 8,\n height: isHorizontal ? containerRect.height - 8 : 1,\n },\n }\n }\n\n const containerRect = container.getBoundingClientRect()\n let insertBefore: HTMLElement | null = null\n let indicatorPosition = 0\n\n for (let i = 0; i < children.length; i++) {\n const child = children[i]\n const rect = child.getBoundingClientRect()\n const midpoint = isHorizontal\n ? rect.left + rect.width / 2\n : rect.top + rect.height / 2\n\n const pointer = isHorizontal ? pointerX : pointerY\n\n const beforeMidpoint = isReversed ? pointer > midpoint : pointer < midpoint\n\n if (beforeMidpoint) {\n insertBefore = child\n indicatorPosition = isHorizontal ? rect.left : rect.top\n break\n }\n }\n\n if (!insertBefore) {\n const lastChild = children[children.length - 1]\n const lastRect = lastChild.getBoundingClientRect()\n indicatorPosition = isHorizontal ? lastRect.right : lastRect.bottom\n }\n\n const indicator: DropIndicator = isHorizontal\n ? {\n x: indicatorPosition,\n y: containerRect.top + 4,\n width: 2,\n height: containerRect.height - 8,\n }\n : {\n x: containerRect.left + 4,\n y: indicatorPosition,\n width: containerRect.width - 8,\n height: 2,\n }\n\n return { insertBefore, indicator }\n}\n\n// Accesses React fiber internals to find the component stack. This is an undocumented\n// API that could change between React versions, but is a common pattern for dev tools.\n// Returns an empty array gracefully if React internals are unavailable.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getFiberForElement(element: HTMLElement): any | null {\n if (typeof window !== 'undefined') {\n const devtools = window.__DIRECT_EDIT_DEVTOOLS__\n if (devtools?.getFiberForElement) {\n const fiber = devtools.getFiberForElement(element)\n if (fiber) return fiber as any\n }\n }\n\n const fiberKey = Object.keys(element).find(\n (key) => key.startsWith('__reactFiber$') || key.startsWith('__reactInternalInstance$')\n )\n\n if (!fiberKey) return null\n return (element as any)[fiberKey] || null\n}\n\ntype ParsedStackFrame = {\n functionName?: string\n fileName?: string\n lineNumber?: number\n columnNumber?: number\n source?: string\n isServer?: boolean\n}\n\nconst STACK_SOURCE_FILE_EXTENSION_REGEX = /\\.(jsx|tsx|ts|js)$/\nconst STACK_BUNDLED_FILE_PATTERN_REGEX =\n /(\\.min|bundle|chunk|vendor|vendors|runtime|polyfill|polyfills)\\.(js|mjs|cjs)$|(chunk|bundle|vendor|vendors|runtime|polyfill|polyfills|framework|app|main|index)[-_.][A-Za-z0-9_-]{4,}\\.(js|mjs|cjs)$|[\\da-f]{8,}\\.(js|mjs|cjs)$|[-_.][\\da-f]{20,}\\.(js|mjs|cjs)$|\\/dist\\/|\\/build\\/|\\/.next\\/|\\/out\\/|\\/node_modules\\/|\\.webpack\\.|\\.vite\\.|\\.turbopack\\./i\nconst FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\\S+:\\d+/\nconst SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\\[native code\\])?$/\nconst SERVER_FRAME_MARKER = '(at Server)'\n\nconst STACK_INTERNAL_SCHEME_PREFIXES = [\n 'rsc://',\n 'about://React/',\n 'React/Server/',\n 'file:///',\n 'webpack://',\n 'webpack-internal://',\n 'node:',\n 'turbopack://',\n '/app-pages-browser/',\n] as const\n\nfunction formatOwnerDebugStack(stack: string): string {\n if (!stack) return ''\n\n const lines = stack.split('\\n')\n const filtered: string[] = []\n\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed) continue\n if (trimmed === 'Error: react-stack-top-frame') continue\n if (\n trimmed.includes('react_stack_bottom_frame') ||\n trimmed.includes('react-stack-bottom-frame')\n ) {\n continue\n }\n filtered.push(line)\n }\n\n if (filtered.length > 0 && filtered[0].includes('fakeJSXCallSite')) {\n filtered.shift()\n }\n\n return filtered.join('\\n')\n}\n\nfunction extractStackLocation(urlLike: string): [string, number | undefined, number | undefined] {\n if (!urlLike.includes(':')) return [urlLike, undefined, undefined]\n\n const isWrappedLocation = urlLike.startsWith('(') && /:\\d+\\)$/.test(urlLike)\n const sanitizedResult = isWrappedLocation ? urlLike.slice(1, -1) : urlLike\n const parts = /(.+?)(?::(\\d+))?(?::(\\d+))?$/.exec(sanitizedResult)\n if (!parts) return [sanitizedResult, undefined, undefined]\n\n return [\n parts[1],\n parts[2] !== undefined ? Number(parts[2]) : undefined,\n parts[3] !== undefined ? Number(parts[3]) : undefined,\n ]\n}\n\nfunction parseV8StackLine(line: string): ParsedStackFrame | null {\n let currentLine = line\n if (currentLine.includes('(eval ')) {\n currentLine = currentLine\n .replace(/eval code/g, 'eval')\n .replace(/(\\(eval at [^()]*)|(,.*$)/g, '')\n }\n\n let sanitizedLine = currentLine\n .replace(/^\\s+/, '')\n .replace(/\\(eval code/g, '(')\n .replace(/^.*?\\s+/, '')\n const locationMatch = sanitizedLine.match(/ (\\(.+\\)$)/)\n if (locationMatch) {\n sanitizedLine = sanitizedLine.replace(locationMatch[0], '')\n }\n\n const [fileName, lineNumber, columnNumber] = extractStackLocation(\n locationMatch ? locationMatch[1] : sanitizedLine\n )\n const functionName = locationMatch && sanitizedLine ? sanitizedLine : undefined\n if (fileName === 'eval' || fileName === '<anonymous>') {\n return {\n functionName,\n }\n }\n\n return {\n functionName,\n fileName,\n lineNumber,\n columnNumber,\n source: currentLine,\n isServer: currentLine.includes(SERVER_FRAME_MARKER) || fileName.startsWith('rsc://'),\n }\n}\n\nfunction parseFFOrSafariStackLine(line: string): ParsedStackFrame | null {\n let currentLine = line\n if (currentLine.includes(' > eval')) {\n currentLine = currentLine.replace(\n / line (\\d+)(?: > eval line \\d+)* > eval:\\d+:\\d+/g,\n ':$1'\n )\n }\n\n const trimmed = currentLine.trim()\n if (!trimmed || SAFARI_NATIVE_CODE_REGEXP.test(trimmed)) {\n return null\n }\n\n if (!trimmed.includes('@') && !trimmed.includes(':')) {\n return {\n functionName: trimmed,\n source: currentLine,\n isServer: trimmed.includes(SERVER_FRAME_MARKER),\n }\n }\n\n const atIndex = trimmed.lastIndexOf('@')\n if (atIndex === -1) {\n return null\n }\n const maybeFunctionName = trimmed.slice(0, atIndex)\n const location = trimmed.slice(atIndex + 1)\n const [fileName, lineNumber, columnNumber] = extractStackLocation(location)\n\n return {\n functionName: maybeFunctionName || undefined,\n fileName,\n lineNumber,\n columnNumber,\n source: currentLine,\n isServer: currentLine.includes(SERVER_FRAME_MARKER) || fileName.startsWith('rsc://'),\n }\n}\n\nfunction parseInStackLine(line: string): ParsedStackFrame | null {\n const functionName = line\n .replace(/^\\s*in\\s+/, '')\n .replace(/\\s*\\(at .*\\)$/, '')\n .trim()\n if (!functionName) return null\n\n return {\n functionName,\n source: line,\n isServer: line.includes(SERVER_FRAME_MARKER),\n }\n}\n\nfunction parseDebugStack(stack: string): ParsedStackFrame[] {\n const frames: ParsedStackFrame[] = []\n for (const rawLine of stack.split('\\n')) {\n if (FIREFOX_SAFARI_STACK_REGEXP.test(rawLine)) {\n const parsed = parseFFOrSafariStackLine(rawLine)\n if (parsed) frames.push(parsed)\n continue\n }\n\n if (/^\\s*at\\s+/.test(rawLine)) {\n const parsed = parseV8StackLine(rawLine)\n if (parsed) frames.push(parsed)\n continue\n }\n\n if (/^\\s*in\\s+/.test(rawLine)) {\n const parsed = parseInStackLine(rawLine)\n if (parsed) frames.push(parsed)\n }\n }\n\n return frames\n}\n\nfunction normalizeStackFileName(fileName: string): string {\n if (!fileName) return ''\n\n let normalized = fileName\n const isHttpUrl = normalized.startsWith('http://') || normalized.startsWith('https://')\n if (isHttpUrl) {\n try {\n normalized = new URL(normalized).pathname\n } catch {\n // Fall through and use the original string.\n }\n }\n\n let didStripPrefix = true\n while (didStripPrefix) {\n didStripPrefix = false\n for (const prefix of STACK_INTERNAL_SCHEME_PREFIXES) {\n if (normalized.startsWith(prefix)) {\n normalized = normalized.slice(prefix.length)\n if (prefix === 'file:///') {\n normalized = `/${normalized.replace(/^\\/+/, '')}`\n }\n didStripPrefix = true\n break\n }\n }\n }\n\n normalized = normalized\n .replace(/^\\/\\(app-pages-browser\\)\\//, '/')\n .replace(/^\\/\\.\\//, '/')\n .replace(/^\\.\\//, '')\n\n const queryIndex = normalized.indexOf('?')\n if (queryIndex !== -1) {\n normalized = normalized.slice(0, queryIndex)\n }\n\n return normalized\n}\n\nfunction isSourceStackFile(fileName: string): boolean {\n const normalizedFileName = normalizeStackFileName(fileName)\n if (!normalizedFileName) return false\n if (!STACK_SOURCE_FILE_EXTENSION_REGEX.test(normalizedFileName)) return false\n return !STACK_BUNDLED_FILE_PATTERN_REGEX.test(normalizedFileName)\n}\n\ntype EnrichedServerFrame = {\n fileName: string\n lineNumber?: number\n columnNumber?: number\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction buildFunctionNameToRscFramesMap(fiber: any): Map<string, EnrichedServerFrame[]> {\n const functionNameToRscFrames = new Map<string, EnrichedServerFrame[]>()\n const visited = new Set<any>()\n let current = fiber\n\n while (current && !visited.has(current)) {\n visited.add(current)\n const rawStack = current?._debugStack?.stack\n const stack = typeof rawStack === 'string' ? formatOwnerDebugStack(rawStack) : ''\n if (stack) {\n const frames = parseDebugStack(stack)\n for (const frame of frames) {\n if (!frame.functionName || !frame.fileName) continue\n if (!frame.fileName.startsWith('rsc://')) continue\n\n const normalized = normalizeStackFileName(frame.fileName)\n if (!normalized) continue\n\n const existing = functionNameToRscFrames.get(frame.functionName) ?? []\n const duplicate = existing.some(\n (candidate) =>\n candidate.fileName === normalized &&\n candidate.lineNumber === frame.lineNumber &&\n candidate.columnNumber === frame.columnNumber\n )\n if (!duplicate) {\n existing.push({\n fileName: normalized,\n lineNumber: frame.lineNumber,\n columnNumber: frame.columnNumber,\n })\n functionNameToRscFrames.set(frame.functionName, existing)\n }\n }\n }\n\n current = current._debugOwner ?? current.return ?? null\n }\n\n return functionNameToRscFrames\n}\n\nfunction enrichServerFrame(\n frame: ParsedStackFrame,\n functionNameToRscFrames: Map<string, EnrichedServerFrame[]>,\n functionNameToUsageIndex: Map<string, number>,\n): ParsedStackFrame {\n if (!frame.functionName) return frame\n\n const available = functionNameToRscFrames.get(frame.functionName)\n if (!available) return frame\n\n const usageIndex = functionNameToUsageIndex.get(frame.functionName) ?? 0\n const resolved = available[usageIndex % available.length]\n functionNameToUsageIndex.set(frame.functionName, usageIndex + 1)\n\n return {\n ...frame,\n fileName: resolved.fileName,\n lineNumber: resolved.lineNumber,\n columnNumber: resolved.columnNumber,\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getSourceFromDebugStack(fiber: any):\n | {\n fileName?: string\n lineNumber?: number\n columnNumber?: number\n }\n | null {\n const rawStack = fiber?._debugStack?.stack\n if (typeof rawStack !== 'string' || rawStack.length === 0) {\n return null\n }\n\n const formattedStack = formatOwnerDebugStack(rawStack)\n if (!formattedStack) return null\n\n const stackFrames = parseDebugStack(formattedStack)\n const functionNameToRscFrames = buildFunctionNameToRscFramesMap(fiber)\n const functionNameToUsageIndex = new Map<string, number>()\n\n for (const frame of stackFrames) {\n const maybeEnriched = frame.isServer\n ? enrichServerFrame(frame, functionNameToRscFrames, functionNameToUsageIndex)\n : frame\n if (!maybeEnriched.fileName) continue\n\n const normalizedFileName = normalizeStackFileName(maybeEnriched.fileName)\n if (!normalizedFileName) continue\n\n if (isSourceStackFile(normalizedFileName)) {\n return {\n fileName: normalizedFileName,\n lineNumber: maybeEnriched.lineNumber,\n columnNumber: maybeEnriched.columnNumber,\n }\n }\n }\n\n return null\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getSourceFromFiber(fiber: any):\n | {\n fileName?: string\n lineNumber?: number\n columnNumber?: number\n }\n | null {\n const debugSource = fiber?._debugSource\n if (debugSource?.fileName) return debugSource\n\n const owner = fiber?._debugOwner\n const ownerPending = owner?.pendingProps?.__source\n if (ownerPending?.fileName) return ownerPending\n\n const ownerMemo = owner?.memoizedProps?.__source\n if (ownerMemo?.fileName) return ownerMemo\n\n const pending = fiber?.pendingProps?.__source\n if (pending?.fileName) return pending\n\n const memo = fiber?.memoizedProps?.__source\n if (memo?.fileName) return memo\n\n const fromDebugStack = getSourceFromDebugStack(fiber)\n if (fromDebugStack?.fileName) return fromDebugStack\n\n return null\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction buildFrame(fiber: any): ReactComponentFrame | null {\n const type = fiber?.type\n if (typeof type !== 'function' && typeof type !== 'object') return null\n\n const name = type?.displayName || type?.name || null\n if (!name || name === 'Fragment') return null\n\n const frame: ReactComponentFrame = { name }\n const source = getSourceFromFiber(fiber)\n if (source?.fileName) {\n frame.file = source.fileName\n if (typeof source.lineNumber === 'number') {\n frame.line = source.lineNumber\n }\n if (typeof source.columnNumber === 'number') {\n frame.column = source.columnNumber\n }\n }\n\n return frame\n}\n\nfunction shouldIncludeFrame(\n frame: ReactComponentFrame,\n lastFrame: ReactComponentFrame | null\n): boolean {\n if (!lastFrame) return true\n if (frame.name !== lastFrame.name) return true\n if (!lastFrame.file && frame.file) return true\n if (lastFrame.file && frame.file && lastFrame.line == null && frame.line != null) return true\n if (\n lastFrame.file &&\n frame.file &&\n lastFrame.line != null &&\n frame.line != null &&\n lastFrame.column == null &&\n frame.column != null\n ) {\n return true\n }\n return false\n}\n\ninterface ComponentWalkResult {\n frames: ReactComponentFrame[]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n nearestComponentFiber: any | null\n elementSourceFile?: string\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getOwnerStack(fiber: any): ComponentWalkResult {\n const frames: ReactComponentFrame[] = []\n let current = fiber\n let lastFrame: ReactComponentFrame | null = null\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let nearestComponentFiber: any | null = null\n\n while (current) {\n const frame = buildFrame(current)\n if (frame && shouldIncludeFrame(frame, lastFrame)) {\n frames.push(frame)\n lastFrame = frame\n if (!nearestComponentFiber) {\n nearestComponentFiber = current\n }\n }\n current = current._debugOwner\n }\n\n return { frames, nearestComponentFiber }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getRenderStack(fiber: any): ComponentWalkResult {\n const frames: ReactComponentFrame[] = []\n let current = fiber\n let lastFrame: ReactComponentFrame | null = null\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let nearestComponentFiber: any | null = null\n\n while (current) {\n const frame = buildFrame(current)\n if (frame && shouldIncludeFrame(frame, lastFrame)) {\n frames.push(frame)\n lastFrame = frame\n if (!nearestComponentFiber) {\n nearestComponentFiber = current\n }\n }\n current = current.return\n }\n\n return { frames, nearestComponentFiber }\n}\n\nfunction getReactComponentInfo(element: HTMLElement): ComponentWalkResult {\n const fiber = getFiberForElement(element)\n if (!fiber) return { frames: [], nearestComponentFiber: null }\n\n const elementSource = getSourceFromFiber(fiber)\n const elementSourceFile = elementSource?.fileName || undefined\n\n const ownerResult = getOwnerStack(fiber)\n if (ownerResult.frames.length > 0) {\n return { ...ownerResult, elementSourceFile }\n }\n\n return { ...getRenderStack(fiber), elementSourceFile }\n}\n\nfunction getReactComponentStack(element: HTMLElement): ReactComponentFrame[] {\n return getReactComponentInfo(element).frames\n}\n\ninterface ChildBriefInfo {\n name: string\n textPreview: string\n source: DomSourceLocation | null\n}\n\nexport function getElementDisplayName(element: HTMLElement): string {\n const tag = element.tagName.toLowerCase()\n if (element.id) return `${tag}#${element.id}`\n const firstClass = Array.from(element.classList)\n .find(c => c && !c.startsWith('direct-edit'))\n if (firstClass) return `${tag}.${firstClass}`\n return tag\n}\n\n/** Lightweight info for a child element, used in reorder data. Does NOT call getElementLocator. */\nexport function getChildBriefInfo(element: HTMLElement): ChildBriefInfo {\n const name = getElementDisplayName(element)\n const raw = ((element.innerText || element.textContent) ?? '').replace(/\\s+/g, ' ').trim()\n const textPreview = raw.length > 40 ? `${raw.slice(0, 37)}...` : raw\n const source = getElementSource(element)\n return { name, textPreview, source }\n}\n\nconst STABLE_ATTRIBUTES = ['data-testid', 'data-qa', 'data-cy', 'aria-label', 'role'] as const\nconst MAX_SELECTOR_DEPTH = 24\nconst CONTEXT_ALLOWED_ATTRIBUTES = new Set([\n 'id',\n 'class',\n 'href',\n 'src',\n 'alt',\n 'aria-label',\n 'role',\n 'data-testid',\n 'data-qa',\n 'data-cy',\n 'data-direct-edit-target',\n])\n\nfunction escapeCssIdentifier(value: string): string {\n if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {\n return CSS.escape(value)\n }\n return value.replace(/[^a-zA-Z0-9_-]/g, (char) => `\\\\${char}`)\n}\n\nfunction escapeAttributeValue(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')\n}\n\nfunction isUniqueSelector(selector: string): boolean {\n if (typeof document === 'undefined') return false\n try {\n return document.querySelectorAll(selector).length === 1\n } catch {\n return false\n }\n}\n\nfunction getUniqueIdSelector(element: HTMLElement): string | null {\n if (!element.id) return null\n const selector = `#${escapeCssIdentifier(element.id)}`\n return isUniqueSelector(selector) ? selector : null\n}\n\nfunction getStableAttributeSelector(element: HTMLElement): string | null {\n const tagName = element.tagName.toLowerCase()\n for (const attr of STABLE_ATTRIBUTES) {\n const value = element.getAttribute(attr)\n if (!value) continue\n const selector = `${tagName}[${attr}=\"${escapeAttributeValue(value)}\"]`\n if (isUniqueSelector(selector)) {\n return selector\n }\n }\n return null\n}\n\nfunction getNthOfTypeSelector(element: HTMLElement): string {\n const tagName = element.tagName.toLowerCase()\n const classes = Array.from(element.classList)\n .filter((className) => className && !className.startsWith('direct-edit'))\n .slice(0, 2)\n const classSelector = classes.map((className) => `.${escapeCssIdentifier(className)}`).join('')\n\n let nthOfType = ''\n const parent = element.parentElement\n if (parent) {\n const siblings = Array.from(parent.children).filter(\n (child) => (child as HTMLElement).tagName.toLowerCase() === tagName\n )\n if (siblings.length > 1) {\n const index = siblings.indexOf(element) + 1\n nthOfType = `:nth-of-type(${index})`\n }\n }\n\n return `${tagName}${classSelector}${nthOfType}`\n}\n\nfunction buildDomSelector(element: HTMLElement): string {\n if (typeof document === 'undefined') {\n return element.tagName.toLowerCase()\n }\n if (element.closest('[data-direct-edit]')) return ''\n\n const uniqueId = getUniqueIdSelector(element)\n if (uniqueId) return uniqueId\n\n const stableAttribute = getStableAttributeSelector(element)\n if (stableAttribute) return stableAttribute\n\n const segments: string[] = []\n let current: HTMLElement | null = element\n let depth = 0\n\n while (current && current !== document.body && depth < MAX_SELECTOR_DEPTH) {\n if (current.hasAttribute('data-direct-edit')) {\n current = current.parentElement\n continue\n }\n\n if (depth > 0) {\n const parentId = getUniqueIdSelector(current)\n if (parentId) {\n segments.unshift(parentId)\n break\n }\n const parentStableAttr = getStableAttributeSelector(current)\n if (parentStableAttr) {\n segments.unshift(parentStableAttr)\n break\n }\n }\n\n segments.unshift(getNthOfTypeSelector(current))\n current = current.parentElement\n depth += 1\n }\n\n return segments.join(' > ')\n}\n\nfunction stripDirectEditNodes(root: Element) {\n const nodes = root.querySelectorAll('[data-direct-edit]')\n nodes.forEach((node) => node.remove())\n}\n\nfunction sanitizeContextNode(root: HTMLElement) {\n const nodes: HTMLElement[] = [root, ...Array.from(root.querySelectorAll<HTMLElement>('*'))]\n for (const node of nodes) {\n for (const attr of Array.from(node.attributes)) {\n if (!CONTEXT_ALLOWED_ATTRIBUTES.has(attr.name)) {\n node.removeAttribute(attr.name)\n }\n }\n }\n}\n\nfunction buildTargetHtml(element: HTMLElement): string {\n const tagName = element.tagName.toLowerCase()\n const attrs: string[] = []\n const allowList = [\n 'id',\n 'class',\n 'href',\n 'src',\n 'alt',\n 'aria-label',\n 'role',\n 'data-testid',\n ]\n const maxAttrLength = 48\n\n for (const attr of allowList) {\n const value = element.getAttribute(attr)\n if (!value) continue\n const trimmed = value.length > maxAttrLength ? `${value.slice(0, maxAttrLength - 3)}...` : value\n attrs.push(`${attr}=\"${escapeAttributeValue(trimmed)}\"`)\n }\n\n const text = getTextPreview(element)\n const attrString = attrs.length > 0 ? ` ${attrs.join(' ')}` : ''\n\n if (text) {\n return `<${tagName}${attrString}>\\n ${escapeHtml(text)}\\n</${tagName}>`\n }\n\n return `<${tagName}${attrString}></${tagName}>`\n}\n\nfunction formatSourcePath(file: string): string {\n const normalized = file\n .replace(/\\\\/g, '/')\n .replace(/^webpack:\\/\\/\\//, '')\n .replace(/^webpack:\\/\\//, '')\n .replace(/^webpack-internal:\\/\\//, '')\n .replace(/^rsc:\\/\\/React\\/Server\\//, '')\n .replace(/^about:\\/\\/React\\//, '')\n .replace(/^file:\\/\\//, '')\n .replace(/^\\/\\(app-pages-browser\\)\\//, '/')\n .replace(/^\\/app-pages-browser\\//, '/')\n .replace(/^_N_E\\//, '')\n .replace(/^\\.\\/+/, '')\n const packagesIndex = normalized.indexOf('/packages/')\n if (packagesIndex !== -1) {\n return `/[project]${normalized.slice(packagesIndex)}`\n }\n const appIndex = normalized.indexOf('/app/')\n if (appIndex !== -1) {\n return `/[project]${normalized.slice(appIndex)}`\n }\n const srcIndex = normalized.indexOf('/src/')\n if (srcIndex !== -1) {\n return `/[project]${normalized.slice(srcIndex)}`\n }\n return normalized\n}\n\nfunction formatSourceLocation(file: string, line?: number, column?: number): string {\n const formatted = formatSourcePath(file)\n if (typeof line === 'number') {\n const columnSuffix = typeof column === 'number' ? `:${column}` : ''\n return `${formatted}:${line}${columnSuffix}`\n }\n return formatted\n}\n\nfunction isUserlandSource(file: string): boolean {\n const normalized = file.replace(/\\\\/g, '/')\n if (\n normalized.includes('node_modules') ||\n normalized.includes('next/dist') ||\n normalized.includes('react') ||\n normalized.includes('react-dom') ||\n normalized.includes('direct-edit')\n ) {\n return false\n }\n return (\n normalized.includes('/app/') ||\n normalized.includes('/src/') ||\n normalized.includes('/packages/') ||\n normalized.startsWith('./')\n )\n}\n\nfunction getPrimaryFrame(locator: ElementLocator): ReactComponentFrame | null {\n for (const frame of locator.reactStack) {\n if (frame.file && isUserlandSource(frame.file)) {\n return frame\n }\n }\n for (const frame of locator.reactStack) {\n if (frame.file) {\n return frame\n }\n }\n return locator.reactStack[0] ?? null\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n}\n\nfunction buildDomContextHtml(\n element: HTMLElement,\n options?: { siblingCount?: number }\n): string {\n const parent = element.parentElement\n if (!parent) {\n const clone = element.cloneNode(true) as HTMLElement\n clone.setAttribute('data-direct-edit-target', 'true')\n stripDirectEditNodes(clone)\n sanitizeContextNode(clone)\n return clone.outerHTML\n }\n\n const parentClone = parent.cloneNode(false) as HTMLElement\n const siblings = Array.from(parent.children) as HTMLElement[]\n const selectedIndex = siblings.indexOf(element)\n const siblingCount = options?.siblingCount ?? 1\n let slice = siblings\n\n if (siblingCount >= 0 && selectedIndex >= 0) {\n const start = Math.max(0, selectedIndex - siblingCount)\n const end = Math.min(siblings.length, selectedIndex + siblingCount + 1)\n slice = siblings.slice(start, end)\n }\n\n for (const sibling of slice) {\n if (sibling.closest('[data-direct-edit]')) continue\n const clone = sibling.cloneNode(true) as HTMLElement\n if (sibling === element) {\n clone.setAttribute('data-direct-edit-target', 'true')\n }\n stripDirectEditNodes(clone)\n sanitizeContextNode(clone)\n parentClone.appendChild(clone)\n }\n\n sanitizeContextNode(parentClone)\n return parentClone.outerHTML\n}\n\nfunction normalizePreviewWhitespace(value: string): string {\n return value.replace(/\\s+/g, ' ').trim()\n}\n\nfunction isWordLikeChar(char: string): boolean {\n return /[A-Za-z0-9]/.test(char)\n}\n\nfunction getFallbackTextPreview(element: HTMLElement): string {\n const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT)\n const tokens: string[] = []\n let previousRaw = ''\n let previousParent: HTMLElement | null = null\n\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n const textNode = node as Text\n const raw = textNode.textContent ?? ''\n const normalized = normalizePreviewWhitespace(raw)\n if (!normalized) continue\n\n if (tokens.length > 0) {\n const hasExplicitWhitespace = /^\\s/.test(raw) || /\\s$/.test(previousRaw)\n const prevLast = previousRaw.slice(-1)\n const nextFirst = normalized[0]\n const shouldInsertHeuristicSpace =\n previousParent !== textNode.parentElement &&\n isWordLikeChar(prevLast) &&\n isWordLikeChar(nextFirst)\n\n if (hasExplicitWhitespace || shouldInsertHeuristicSpace) {\n tokens.push(' ')\n }\n }\n\n tokens.push(normalized)\n previousRaw = raw\n previousParent = textNode.parentElement\n }\n\n return tokens.join('')\n}\n\nfunction getTextPreview(element: HTMLElement): string {\n const innerTextCandidate = normalizePreviewWhitespace(element.innerText ?? '')\n const text = innerTextCandidate || getFallbackTextPreview(element)\n if (text.length <= 120) {\n return text\n }\n return `${text.slice(0, 117)}...`\n}\n\nfunction parseDomSource(element: HTMLElement): DomSourceLocation | null {\n const value = element.getAttribute('data-direct-edit-source')\n if (!value) return null\n\n let file = value\n let line: number | undefined\n let column: number | undefined\n\n const lastColon = value.lastIndexOf(':')\n if (lastColon !== -1) {\n const maybeColumn = Number(value.slice(lastColon + 1))\n if (!Number.isNaN(maybeColumn)) {\n column = maybeColumn\n file = value.slice(0, lastColon)\n\n const prevColon = file.lastIndexOf(':')\n if (prevColon !== -1) {\n const maybeLine = Number(file.slice(prevColon + 1))\n if (!Number.isNaN(maybeLine)) {\n line = maybeLine\n file = file.slice(0, prevColon)\n }\n }\n }\n }\n\n return { file, line, column }\n}\n\nconst MAX_SUB_ELEMENT_SOURCES = 20\n\nfunction collectSubElementSources(element: HTMLElement): Record<string, DomSourceLocation> {\n const sources: Record<string, DomSourceLocation> = {}\n const children = element.querySelectorAll('[data-direct-edit-source]')\n const labelCounts = new Map<string, number>()\n let count = 0\n\n for (const child of children) {\n if (count >= MAX_SUB_ELEMENT_SOURCES) break\n if (!(child instanceof HTMLElement)) continue\n const source = parseDomSource(child)\n if (!source) continue\n\n const text = ((child.innerText || child.textContent) ?? '').trim()\n let baseLabel = text.length > 0 && text.length <= 30\n ? text.slice(0, 30).toLowerCase().replace(/\\s+/g, '_')\n : child.tagName.toLowerCase()\n\n const existing = labelCounts.get(baseLabel) ?? 0\n labelCounts.set(baseLabel, existing + 1)\n const label = existing > 0 ? `${baseLabel}_${existing + 1}` : baseLabel\n\n sources[label] = source\n count++\n }\n\n return sources\n}\n\n/** Resolve the source location for an element: data-direct-edit-source attribute, then fiber fallback. */\nexport function getElementSource(element: HTMLElement): DomSourceLocation | null {\n const domSource = parseDomSource(element)\n if (domSource) return domSource\n\n // Fallback: get source from the element's own React fiber when\n // the Vite plugin attribute is not present\n const seenFibers = new Set<any>()\n let fiber = getFiberForElement(element)\n while (fiber && !seenFibers.has(fiber)) {\n seenFibers.add(fiber)\n const fiberSource = getSourceFromFiber(fiber)\n if (fiberSource?.fileName) {\n return {\n file: fiberSource.fileName,\n line: fiberSource.lineNumber,\n column: fiberSource.columnNumber,\n }\n }\n fiber = fiber._debugOwner ?? fiber.return ?? null\n }\n return null\n}\n\nexport function getElementLocator(element: HTMLElement): ElementLocator {\n const elementInfo = getElementInfo(element)\n const domSource = getElementSource(element)\n const { frames, nearestComponentFiber, elementSourceFile } = getReactComponentInfo(element)\n\n const componentName = nearestComponentFiber?.type?.displayName\n || nearestComponentFiber?.type?.name\n || undefined\n\n const authoredProps = nearestComponentFiber\n ? getComponentProps(nearestComponentFiber)\n : undefined\n\n const classification = classifyComponentFiber(nearestComponentFiber, frames, elementSourceFile)\n\n const callSite = nearestComponentFiber\n ? getCallSiteSource(nearestComponentFiber)\n : null\n\n const definitionSrc = classification.isComponentPrimitive\n ? deriveDefinitionSource(frames)\n : null\n\n const subSources = collectSubElementSources(element)\n\n return {\n reactStack: frames,\n domSelector: buildDomSelector(element),\n domContextHtml: buildDomContextHtml(element),\n targetHtml: buildTargetHtml(element),\n textPreview: getTextPreview(element),\n tagName: elementInfo.tagName,\n id: elementInfo.id,\n classList: elementInfo.classList,\n domSource: domSource ?? undefined,\n reactComponentName: componentName,\n authoredProps: authoredProps && Object.keys(authoredProps).length > 0 ? authoredProps : undefined,\n subElementSources: Object.keys(subSources).length > 0 ? subSources : undefined,\n callSiteSource: callSite ?? undefined,\n definitionSource: definitionSrc ?? undefined,\n isComponentPrimitive: (nearestComponentFiber || elementSourceFile) ? classification.isComponentPrimitive : undefined,\n }\n}\n\ninterface ExportChange {\n property: string\n value: string\n tailwind: string\n}\n\nexport function getLocatorHeader(locator: ElementLocator): {\n componentLabel: string\n formattedSource: string | null\n formattedCallSite: string | null\n} {\n const primaryFrame = getPrimaryFrame(locator)\n const componentLabel = locator.reactComponentName ?? primaryFrame?.name ?? locator.tagName\n\n // Classification-aware source resolution (decision 8A):\n // For component primitives with definitionSource → use definition\n // Otherwise → existing logic (domSource, then primary frame)\n let formattedSource: string | null\n if (locator.isComponentPrimitive && locator.definitionSource?.file) {\n formattedSource = formatSourceLocation(\n locator.definitionSource.file,\n locator.definitionSource.line,\n locator.definitionSource.column,\n )\n } else {\n formattedSource = locator.domSource?.file\n ? formatSourceLocation(locator.domSource.file, locator.domSource.line, locator.domSource.column)\n : primaryFrame?.file\n ? formatSourceLocation(primaryFrame.file, primaryFrame.line, primaryFrame.column)\n : null\n }\n\n const formattedCallSite = locator.callSiteSource?.file\n ? formatSourceLocation(locator.callSiteSource.file, locator.callSiteSource.line, locator.callSiteSource.column)\n : null\n\n return { componentLabel, formattedSource, formattedCallSite }\n}\n\nexport function formatComponentTree(reactStack: ReactComponentFrame[]): string | null {\n const names = reactStack\n .map(f => f.name)\n .filter(Boolean)\n if (names.length === 0) return null\n if (names.length === 1) return names[0]\n const [component, ...ancestors] = names\n return `${component} (in ${ancestors.join(' > ')})`\n}\n\nfunction buildLocatorContextLines(locator: ElementLocator, options?: { skipContext?: boolean }): string[] {\n const lines: string[] = []\n const { componentLabel, formattedSource, formattedCallSite } = getLocatorHeader(locator)\n const target = (locator.targetHtml || locator.domContextHtml || '').trim()\n const context = locator.domContextHtml?.trim() || ''\n const path = locator.domSelector?.trim()\n const text = locator.textPreview?.trim()\n\n lines.push(`@<${componentLabel}>`)\n lines.push('')\n\n // React component tree\n const tree = formatComponentTree(locator.reactStack)\n if (tree) {\n lines.push(`react: ${tree}`)\n }\n\n // Authored props\n if (locator.authoredProps && Object.keys(locator.authoredProps).length > 0) {\n lines.push(`props: ${JSON.stringify(locator.authoredProps)}`)\n }\n\n // Type classification\n if (locator.isComponentPrimitive != null) {\n lines.push(`type: ${locator.isComponentPrimitive ? 'component' : 'instance'}`)\n }\n\n // Source location (classification-aware via getLocatorHeader)\n lines.push(`source: ${formattedSource ?? '(file not available)'}`)\n\n // Call-site (always included when available)\n if (formattedCallSite && formattedCallSite !== formattedSource) {\n lines.push(`call-site: ${formattedCallSite}`)\n }\n\n // Sub-element source map\n if (locator.subElementSources && Object.keys(locator.subElementSources).length > 0) {\n lines.push('source-map:')\n for (const [label, source] of Object.entries(locator.subElementSources)) {\n lines.push(` - ${label}: ${formatSourceLocation(source.file, source.line, source.column)}`)\n }\n }\n\n // DOM path\n if (path) {\n lines.push(`path: ${path}`)\n }\n\n // Target HTML\n if (target) {\n lines.push('')\n lines.push('target:')\n lines.push(target)\n }\n\n // Context HTML\n if (!options?.skipContext && context && context !== target) {\n lines.push('')\n lines.push('context:')\n lines.push(context)\n }\n\n // Text preview\n if (text) {\n lines.push(`text: ${text}`)\n }\n\n return lines\n}\n\nexport function buildElementContext(locator: ElementLocator): string {\n return buildLocatorContextLines(locator).join('\\n')\n}\n\n/** Whether a session edit has any meaningful changes (styles, text, or move). */\nexport function hasSessionEditChanges(edit: SessionEdit): boolean {\n return Object.keys(edit.pendingStyles).length > 0 || Boolean(edit.textEdit) || Boolean(edit.move)\n}\n\n/**\n * Partition multi-selected elements into edits with changes vs context-only blocks.\n * Returns the edits that have meaningful changes and context markdown for the rest.\n */\nexport function partitionMultiSelectedEdits(\n elements: HTMLElement[],\n sessionEditsRef: { current: Map<HTMLElement, SessionEdit> },\n): { editsWithChanges: SessionEdit[]; contextBlocks: string[] } {\n const editsWithChanges: SessionEdit[] = []\n const contextBlocks: string[] = []\n for (const el of elements) {\n if (!el.isConnected) continue\n const edit = sessionEditsRef.current.get(el)\n if (edit && hasSessionEditChanges(edit)) {\n editsWithChanges.push(edit)\n } else {\n contextBlocks.push(buildElementContext(getElementLocator(el)))\n }\n }\n return { editsWithChanges, contextBlocks }\n}\n\n/**\n * Collect context blocks for multi-selected elements not already in a session items list.\n */\nexport function getContextOnlyBlocks(\n selectedElements: HTMLElement[],\n sessionItems: SessionItem[],\n): string[] {\n if (selectedElements.length <= 1) return []\n const sessionElementSet = new Set(\n sessionItems.filter((i) => i.type === 'edit').map((i) => i.edit.element),\n )\n const blocks: string[] = []\n for (const el of selectedElements) {\n if (!el.isConnected || sessionElementSet.has(el)) continue\n blocks.push(buildElementContext(getElementLocator(el)))\n }\n return blocks\n}\n\nconst spacingGroups = [\n { top: 'padding-top', right: 'padding-right', bottom: 'padding-bottom', left: 'padding-left', all: 'padding', inline: 'padding-inline', block: 'padding-block' },\n { top: 'margin-top', right: 'margin-right', bottom: 'margin-bottom', left: 'margin-left', all: 'margin', inline: 'margin-inline', block: 'margin-block' },\n] as const\n\nexport function collapseSpacingShorthands(styles: Record<string, string>): Record<string, string> {\n const result = { ...styles }\n\n for (const group of spacingGroups) {\n const hasTop = group.top in result\n const hasRight = group.right in result\n const hasBottom = group.bottom in result\n const hasLeft = group.left in result\n const hasAllSides = hasTop && hasRight && hasBottom && hasLeft\n\n if (hasAllSides) {\n delete result[group.all]\n delete result[group.inline]\n delete result[group.block]\n }\n\n const top = result[group.top]\n const right = result[group.right]\n const bottom = result[group.bottom]\n const left = result[group.left]\n\n const horizontalMatch = hasLeft && hasRight && left === right\n const verticalMatch = hasTop && hasBottom && top === bottom\n\n if (horizontalMatch && verticalMatch) {\n delete result[group.top]\n delete result[group.right]\n delete result[group.bottom]\n delete result[group.left]\n if (top === left) {\n result[group.all] = top\n } else {\n result[group.inline] = left\n result[group.block] = top\n }\n } else if (horizontalMatch) {\n // Only horizontal pair matches\n delete result[group.left]\n delete result[group.right]\n result[group.inline] = left\n } else if (verticalMatch) {\n // Only vertical pair matches\n delete result[group.top]\n delete result[group.bottom]\n result[group.block] = top\n }\n }\n\n return result\n}\n\nfunction collapseFourSideShorthand(\n result: Record<string, string>,\n sides: { top: string; right: string; bottom: string; left: string; all: string }\n): void {\n if (!(sides.top in result && sides.right in result && sides.bottom in result && sides.left in result)) return\n\n // Side-specific values are the source of truth when all four are present.\n delete result[sides.all]\n\n const top = result[sides.top]\n const right = result[sides.right]\n const bottom = result[sides.bottom]\n const left = result[sides.left]\n const allEqual = top === right && top === bottom && top === left\n if (!allEqual) return\n\n delete result[sides.top]\n delete result[sides.right]\n delete result[sides.bottom]\n delete result[sides.left]\n result[sides.all] = top\n}\n\nexport function collapseExportShorthands(styles: Record<string, string>): Record<string, string> {\n const result = collapseSpacingShorthands(styles)\n\n collapseFourSideShorthand(result, {\n top: 'border-top-style',\n right: 'border-right-style',\n bottom: 'border-bottom-style',\n left: 'border-left-style',\n all: 'border-style',\n })\n\n collapseFourSideShorthand(result, {\n top: 'border-top-width',\n right: 'border-right-width',\n bottom: 'border-bottom-width',\n left: 'border-left-width',\n all: 'border-width',\n })\n\n collapseFourSideShorthand(result, {\n top: 'border-top-left-radius',\n right: 'border-top-right-radius',\n bottom: 'border-bottom-right-radius',\n left: 'border-bottom-left-radius',\n all: 'border-radius',\n })\n\n return result\n}\n\nexport function buildEditExport(\n locator: ElementLocator,\n pendingStyles: Record<string, string>,\n textEdit?: { originalText: string; newText: string } | null\n): string\nexport function buildEditExport(\n element: HTMLElement | null,\n elementInfo: ElementInfo,\n computedSpacing: SpacingProperties | null,\n computedBorderRadius: BorderRadiusProperties | null,\n computedFlex: FlexProperties | null,\n computedSizing: SizingProperties | null,\n pendingStyles: Record<string, string>\n): string\nexport function buildEditExport(\n arg1: ElementLocator | HTMLElement | null,\n arg2: ElementInfo | Record<string, string>,\n arg3?: SpacingProperties | null | { originalText: string; newText: string },\n arg4?: BorderRadiusProperties | null,\n arg5?: FlexProperties | null,\n arg6?: SizingProperties | null,\n arg7?: Record<string, string>\n): string {\n const isLocator = Boolean(arg1 && typeof arg1 === 'object' && 'domSelector' in arg1)\n if (!isLocator) {\n void arg4\n void arg5\n void arg6\n }\n const pendingStyles = (isLocator ? (arg2 as Record<string, string>) : arg7) || {}\n const textEdit = isLocator && arg3 && typeof arg3 === 'object' && 'originalText' in arg3\n ? (arg3 as { originalText: string; newText: string })\n : null\n let locator: ElementLocator\n\n if (isLocator) {\n locator = arg1 as ElementLocator\n } else {\n const element = arg1 as HTMLElement | null\n const elementInfo = arg2 as ElementInfo\n locator = element\n ? getElementLocator(element)\n : {\n reactStack: [],\n domSelector: elementInfo.id ? `#${elementInfo.id}` : elementInfo.tagName,\n domContextHtml: `<${elementInfo.tagName}${elementInfo.id ? ` id=\"${elementInfo.id}\"` : ''} data-direct-edit-target=\"true\"></${elementInfo.tagName}>`,\n targetHtml: `<${elementInfo.tagName}${elementInfo.id ? ` id=\"${elementInfo.id}\"` : ''}></${elementInfo.tagName}>`,\n textPreview: '',\n tagName: elementInfo.tagName,\n id: elementInfo.id,\n classList: elementInfo.classList,\n }\n }\n\n const changes: ExportChange[] = []\n\n const collapsedStyles = collapseExportShorthands(pendingStyles)\n for (const [property, value] of Object.entries(collapsedStyles)) {\n const tailwindClass = stylesToTailwind({ [property]: value })\n changes.push({\n property,\n value,\n tailwind: tailwindClass,\n })\n }\n\n const lines = buildLocatorContextLines(locator)\n lines.push('')\n if (changes.length > 0) {\n lines.push('edits:')\n for (const change of changes) {\n const tailwind = change.tailwind ? ` (${change.tailwind})` : ''\n lines.push(`${change.property}: ${change.value}${tailwind}`)\n }\n }\n\n if (textEdit) {\n lines.push('text content changed:')\n lines.push(`from: \"${textEdit.originalText}\"`)\n lines.push(`to: \"${textEdit.newText}\"`)\n }\n\n return lines.join('\\n')\n}\n\n/** Like buildEditExport but with options to skip context HTML (for move edits). */\nfunction buildEditExportWithOptions(\n locator: ElementLocator,\n pendingStyles: Record<string, string>,\n textEdit?: { originalText: string; newText: string } | null,\n options?: { skipContext?: boolean }\n): string {\n const changes: ExportChange[] = []\n const collapsedStyles = collapseExportShorthands(pendingStyles)\n for (const [property, value] of Object.entries(collapsedStyles)) {\n const tailwindClass = stylesToTailwind({ [property]: value })\n changes.push({ property, value, tailwind: tailwindClass })\n }\n\n const lines = buildLocatorContextLines(locator, options)\n lines.push('')\n if (changes.length > 0) {\n lines.push('edits:')\n for (const change of changes) {\n const tailwind = change.tailwind ? ` (${change.tailwind})` : ''\n lines.push(`${change.property}: ${change.value}${tailwind}`)\n }\n }\n\n if (textEdit) {\n lines.push('text content changed:')\n lines.push(`from: \"${textEdit.originalText}\"`)\n lines.push(`to: \"${textEdit.newText}\"`)\n }\n\n return lines.join('\\n')\n}\n\nexport function buildCommentExport(\n locator: ElementLocator,\n commentText: string,\n replies?: Array<{ text: string; createdAt: number }>\n): string {\n const lines = buildLocatorContextLines(locator)\n lines.push('')\n lines.push(`comment: ${commentText}`)\n if (replies && replies.length > 0) {\n for (const reply of replies) {\n lines.push(`reply: ${reply.text}`)\n }\n }\n\n return lines.join('\\n')\n}\n\nfunction normalizeSelector(selector: string | null | undefined): string | null {\n const value = selector?.trim()\n return value && value.length > 0 ? value : null\n}\n\nfunction normalizeName(name: string | null | undefined): string {\n return name?.trim().toLowerCase() || 'element'\n}\n\nfunction buildAnchorRef(\n name: string | null | undefined,\n selector: string | null | undefined,\n source: DomSourceLocation | null | undefined\n): AnchorRef {\n return {\n name: name?.trim() || 'element',\n selector: normalizeSelector(selector),\n source: source?.file ? source : null,\n }\n}\n\nfunction anchorKey(anchor: AnchorRef | null | undefined): string {\n if (!anchor) return 'none'\n const selector = normalizeSelector(anchor.selector)\n if (selector) return `selector:${selector}`\n if (anchor.source?.file) {\n return `source:${anchor.source.file}:${anchor.source.line ?? 0}:${anchor.source.column ?? 0}`\n }\n return `name:${normalizeName(anchor.name)}`\n}\n\nfunction anchorsEqual(a: AnchorRef | null | undefined, b: AnchorRef | null | undefined): boolean {\n if (!a && !b) return true\n if (!a || !b) return false\n const aSelector = normalizeSelector(a.selector)\n const bSelector = normalizeSelector(b.selector)\n if (aSelector && bSelector) return aSelector === bSelector\n if (a.source?.file && b.source?.file) {\n return (\n a.source.file === b.source.file\n && (a.source.line ?? null) === (b.source.line ?? null)\n && (a.source.column ?? null) === (b.source.column ?? null)\n )\n }\n return normalizeName(a.name) === normalizeName(b.name)\n}\n\nfunction formatAnchorRef(anchor: AnchorRef | null | undefined, fallback = '(none)'): string {\n if (!anchor) return fallback\n const selector = normalizeSelector(anchor.selector)\n if (selector) return selector\n if (anchor.source?.file) return `<${anchor.name}> @ ${formatSourceLocation(anchor.source.file, anchor.source.line, anchor.source.column)}`\n return `<${anchor.name}>`\n}\n\nfunction buildPlacementRef(before: AnchorRef | null, after: AnchorRef | null): PlacementRef {\n if (before && after) {\n return {\n before,\n after,\n description: `between after ${formatAnchorRef(before)} and before ${formatAnchorRef(after)}`,\n }\n }\n if (before) {\n return {\n before,\n after: null,\n description: `after ${formatAnchorRef(before)}`,\n }\n }\n if (after) {\n return {\n before: null,\n after,\n description: `before ${formatAnchorRef(after)}`,\n }\n }\n return {\n before: null,\n after: null,\n description: 'as the only child',\n }\n}\n\nfunction buildPlacementFromMove(\n beforeName: string | null | undefined,\n beforeSelector: string | null | undefined,\n beforeSource: DomSourceLocation | null | undefined,\n afterName: string | null | undefined,\n afterSelector: string | null | undefined,\n afterSource: DomSourceLocation | null | undefined\n): PlacementRef {\n const before = (beforeName || beforeSelector || beforeSource?.file)\n ? buildAnchorRef(beforeName, beforeSelector, beforeSource)\n : null\n const after = (afterName || afterSelector || afterSource?.file)\n ? buildAnchorRef(afterName, afterSelector, afterSource)\n : null\n return buildPlacementRef(before, after)\n}\n\nfunction toRoundedVisualDelta(move: NonNullable<SessionEdit['move']>): { x: number; y: number } | undefined {\n const delta = move.visualDelta ?? move.positionDelta\n if (!delta) return undefined\n const rounded = { x: Math.round(delta.x), y: Math.round(delta.y) }\n return rounded.x === 0 && rounded.y === 0 ? undefined : rounded\n}\n\nfunction hasVisualIntent(move: NonNullable<SessionEdit['move']>): boolean {\n return Boolean(toRoundedVisualDelta(move))\n}\n\nfunction hasStructuralChange(move: NonNullable<SessionEdit['move']>): boolean {\n const fromParent = buildAnchorRef(move.fromParentName, move.fromParentSelector, move.fromParentSource)\n const toParent = buildAnchorRef(move.toParentName, move.toParentSelector, move.toParentSource)\n const fromPlacement = buildPlacementFromMove(\n move.fromSiblingBefore,\n move.fromSiblingBeforeSelector,\n move.fromSiblingBeforeSource,\n move.fromSiblingAfter,\n move.fromSiblingAfterSelector,\n move.fromSiblingAfterSource,\n )\n const toPlacement = buildPlacementFromMove(\n move.toSiblingBefore,\n move.toSiblingBeforeSelector,\n move.toSiblingBeforeSource,\n move.toSiblingAfter,\n move.toSiblingAfterSelector,\n move.toSiblingAfterSource,\n )\n\n if (!anchorsEqual(fromParent, toParent)) return true\n if (!anchorsEqual(fromPlacement.before, toPlacement.before)) return true\n if (!anchorsEqual(fromPlacement.after, toPlacement.after)) return true\n if (typeof move.fromIndex === 'number' && typeof move.toIndex === 'number' && move.fromIndex !== move.toIndex) return true\n return false\n}\n\nfunction isStructuredLayoutContainer(layout: NonNullable<SessionEdit['move']>['fromParentLayout'] | undefined): boolean {\n return layout === 'flex' || layout === 'grid'\n}\n\nfunction isExistingFlexWorkflow(move: NonNullable<SessionEdit['move']>): boolean {\n const structuralChange = hasStructuralChange(move)\n if (!structuralChange) return false\n\n const fromParent = buildAnchorRef(move.fromParentName, move.fromParentSelector, move.fromParentSource)\n const toParent = buildAnchorRef(move.toParentName, move.toParentSelector, move.toParentSource)\n const sameParent = anchorsEqual(fromParent, toParent)\n const fromLayout = move.fromParentLayout\n const toLayout = move.toParentLayout\n\n if (sameParent) {\n return Boolean(move.mode === 'reorder' && (isStructuredLayoutContainer(toLayout) || isStructuredLayoutContainer(fromLayout)))\n }\n return Boolean(isStructuredLayoutContainer(fromLayout) && isStructuredLayoutContainer(toLayout))\n}\n\nfunction classifyMove(move: NonNullable<SessionEdit['move']>): MoveClassification | 'noop' {\n const structuralChange = hasStructuralChange(move)\n const visualIntent = hasVisualIntent(move)\n if (!structuralChange && !visualIntent) return 'noop'\n if (isExistingFlexWorkflow(move)) return 'existing_layout_move'\n if (move.mode === 'free' || move.mode === 'position') return 'layout_refactor'\n if (!structuralChange && visualIntent) return 'layout_refactor'\n return 'layout_refactor'\n}\n\ninterface NumericCluster {\n center: number\n values: number[]\n}\n\nfunction buildNumericClusters(values: number[], tolerance: number): NumericCluster[] {\n if (values.length === 0) return []\n const sorted = [...values].sort((a, b) => a - b)\n const clusters: NumericCluster[] = [{ center: sorted[0], values: [sorted[0]] }]\n for (let i = 1; i < sorted.length; i++) {\n const value = sorted[i]\n const current = clusters[clusters.length - 1]\n if (Math.abs(value - current.center) <= tolerance) {\n current.values.push(value)\n current.center = current.values.reduce((sum, n) => sum + n, 0) / current.values.length\n } else {\n clusters.push({ center: value, values: [value] })\n }\n }\n return clusters\n}\n\nfunction inferFlexDirection(\n sameRowCount: number,\n sameColumnCount: number,\n visualDelta?: { x: number; y: number }\n): { direction: 'row' | 'column'; reason: string } {\n if (sameRowCount > sameColumnCount) {\n return { direction: 'row', reason: 'Subject aligns with neighboring anchors on the same row.' }\n }\n if (sameColumnCount > sameRowCount) {\n return { direction: 'column', reason: 'Subject aligns with neighboring anchors on the same column.' }\n }\n if (sameRowCount > 0) {\n return { direction: 'row', reason: 'Detected row alignment in final geometry.' }\n }\n if (sameColumnCount > 0) {\n return { direction: 'column', reason: 'Detected column alignment in final geometry.' }\n }\n const horizontalDominant = Math.abs(visualDelta?.x ?? 0) >= Math.abs(visualDelta?.y ?? 0)\n return {\n direction: horizontalDominant ? 'row' : 'column',\n reason: 'Fell back to movement axis because anchor alignment was ambiguous.',\n }\n}\n\nfunction inferLayoutPrescription(\n edit: SessionEdit,\n operation: Omit<MoveOperation, 'operationId'>,\n reasons: string[]\n): LayoutPrescription {\n const parent = edit.element.parentElement\n if (!parent || !edit.element.isConnected) {\n return {\n recommendedSystem: 'flex',\n intentPatterns: ['no_geometry_context'],\n refactorSteps: [\n `Reparent ${formatAnchorRef(operation.subject)} under ${formatAnchorRef(operation.to.parent)} at ${operation.to.placement.description}.`,\n ],\n styleSteps: [\n `Convert ${formatAnchorRef(operation.to.parent)} to flex and set a clear primary axis for this relationship.`,\n 'Use `gap` for spacing and keep positioning static.',\n ],\n itemSteps: [\n 'Remove any inline `left/top/transform` move artifacts from moved elements.',\n ],\n }\n }\n\n const children = Array.from(parent.children).filter(\n (node) => node instanceof HTMLElement && isInFlowChild(node) && !node.hasAttribute('data-direct-edit')\n ) as HTMLElement[]\n const childSnapshots = children.map((child) => {\n const rect = child.getBoundingClientRect()\n const locator = getElementLocator(child)\n const anchor = buildAnchorRef(getElementDisplayName(child), locator.domSelector, locator.domSource)\n return {\n child,\n rect,\n centerX: rect.left + rect.width / 2,\n centerY: rect.top + rect.height / 2,\n anchor,\n anchorLabel: formatAnchorRef(anchor),\n }\n })\n const subjectSnapshot = childSnapshots.find((snapshot) => snapshot.child === edit.element)\n const subjectRect = edit.element.getBoundingClientRect()\n const subjectCenterX = subjectRect.left + subjectRect.width / 2\n const subjectCenterY = subjectRect.top + subjectRect.height / 2\n const rowTolerance = Math.max(8, subjectRect.height * 0.35)\n const colTolerance = Math.max(8, subjectRect.width * 0.35)\n\n const sameRowWith: string[] = []\n const sameColumnWith: string[] = []\n const sameRowNodes: typeof childSnapshots = []\n let aboveAnchor: string | null = null\n let belowAnchor: string | null = null\n let bestAboveDistance = Number.POSITIVE_INFINITY\n let bestBelowDistance = Number.POSITIVE_INFINITY\n\n for (const node of childSnapshots) {\n if (node.child === edit.element) continue\n\n if (Math.abs(node.centerY - subjectCenterY) <= rowTolerance) {\n sameRowWith.push(node.anchorLabel)\n sameRowNodes.push(node)\n }\n if (Math.abs(node.centerX - subjectCenterX) <= colTolerance) {\n sameColumnWith.push(node.anchorLabel)\n }\n\n const yDelta = node.centerY - subjectCenterY\n if (yDelta < 0 && Math.abs(yDelta) < bestAboveDistance) {\n bestAboveDistance = Math.abs(yDelta)\n aboveAnchor = node.anchorLabel\n }\n if (yDelta > 0 && yDelta < bestBelowDistance) {\n bestBelowDistance = yDelta\n belowAnchor = node.anchorLabel\n }\n }\n\n const rowCenters = childSnapshots.map(({ centerY }) => centerY)\n const colCenters = childSnapshots.map(({ centerX }) => centerX)\n const rowClusters = buildNumericClusters(rowCenters, rowTolerance)\n const colClusters = buildNumericClusters(colCenters, colTolerance)\n const denseRowClusters = rowClusters.filter(cluster => cluster.values.length >= 2).length\n const denseColClusters = colClusters.filter(cluster => cluster.values.length >= 2).length\n const isTwoDimensional = childSnapshots.length >= 4 && denseRowClusters >= 2 && denseColClusters >= 2\n const recommendedSystem: 'flex' | 'grid' = isTwoDimensional ? 'grid' : 'flex'\n\n const intentPatterns: string[] = []\n if (sameRowWith.length > 0) intentPatterns.push(`same_row_with:${sameRowWith.slice(0, 3).join(', ')}`)\n if (sameColumnWith.length > 0) intentPatterns.push(`same_column_with:${sameColumnWith.slice(0, 3).join(', ')}`)\n if (aboveAnchor) intentPatterns.push(`below:${aboveAnchor}`)\n if (belowAnchor) intentPatterns.push(`above:${belowAnchor}`)\n if (sameRowWith.length === 0 && sameColumnWith.length === 0) intentPatterns.push('separate_cluster')\n\n const visualDelta = operation.visualDelta\n const flexDirectionInfo = inferFlexDirection(sameRowWith.length, sameColumnWith.length, visualDelta)\n const flexDirection = flexDirectionInfo.direction\n\n if (recommendedSystem === 'grid') {\n reasons.push('Detected multiple dense row and column clusters; a 2D layout system is likely intentional.')\n return {\n recommendedSystem: 'grid',\n intentPatterns,\n refactorSteps: [\n `Create/ensure a shared container around ${formatAnchorRef(operation.subject)} and related anchors under ${formatAnchorRef(operation.to.parent)}.`,\n `Reorder/reparent elements to satisfy placement ${operation.to.placement.description}.`,\n ],\n styleSteps: [\n `Set ${formatAnchorRef(operation.to.parent)} to grid with explicit template rows/columns for the final layout.`,\n 'Use `gap` for consistent spacing and keep placement structural.',\n ],\n itemSteps: [\n `Set item alignment on ${formatAnchorRef(operation.subject)} with grid self-alignment (` + '`justify-self`/`align-self`).',\n ],\n }\n }\n\n reasons.push(`${flexDirectionInfo.reason} Use a 1D flex layout instead of literal drag replay.`)\n\n let hasStackedCluster = false\n const stackedAnchorLabels = new Set<string>()\n if (flexDirection === 'row' && subjectSnapshot) {\n for (const rowPeer of sameRowNodes) {\n for (const node of childSnapshots) {\n if (node.child === edit.element || node.child === rowPeer.child) continue\n const sameColumnAsPeer = Math.abs(node.centerX - rowPeer.centerX) <= colTolerance\n const verticallySeparated = Math.abs(node.centerY - rowPeer.centerY) > rowTolerance\n if (sameColumnAsPeer && verticallySeparated) {\n hasStackedCluster = true\n stackedAnchorLabels.add(rowPeer.anchorLabel)\n stackedAnchorLabels.add(node.anchorLabel)\n }\n }\n }\n }\n\n const hasBelowCluster = childSnapshots.some((node) => (\n node.child !== edit.element\n && node.centerY - subjectCenterY > rowTolerance * 1.5\n && Math.abs(node.centerY - subjectCenterY) > Math.abs(node.centerX - subjectCenterX)\n ))\n\n const refactorSteps = [\n `Ensure ${formatAnchorRef(operation.subject)} and referenced neighbors share a common container under ${formatAnchorRef(operation.to.parent)}.`,\n `Reparent/reorder nodes so ${formatAnchorRef(operation.subject)} lands ${operation.to.placement.description}.`,\n ]\n if (flexDirection === 'row' && hasStackedCluster) {\n const clusterSample = Array.from(stackedAnchorLabels).slice(0, 3).join(', ')\n refactorSteps.push(`Create a left-side content wrapper for vertically stacked items (${clusterSample}), and keep ${formatAnchorRef(operation.subject)} as the opposite-side sibling.`)\n }\n if (hasBelowCluster) {\n refactorSteps.push('Keep lower content sections in a separate block below the horizontal header row; do not force them into the same row.')\n }\n\n const styleSteps = [\n `Set ${formatAnchorRef(operation.to.parent)} to flex with direction ${flexDirection}.`,\n flexDirection === 'row'\n ? 'Use `justify-content: space-between` and `align-items: flex-start` when the moved element should sit on the opposite edge.'\n : 'Use `justify-content` / `align-items` to establish top-bottom alignment.',\n 'Use `gap` for spacing between siblings.',\n ]\n if (flexDirection === 'row' && hasStackedCluster) {\n styleSteps.push('Set the content wrapper to `display: flex` with `flex-direction: column` and an appropriate vertical gap.')\n }\n\n return {\n recommendedSystem: 'flex',\n intentPatterns,\n refactorSteps,\n styleSteps,\n itemSteps: [\n `Apply item-level alignment (` + '`align-self`' + ` / flex-basis) only when needed for ${formatAnchorRef(operation.subject)}.`,\n 'Do not use absolute positioning, top/left offsets, transforms, or margin hacks to simulate movement.',\n ],\n }\n}\n\ninterface MovePlanEntry {\n edit: SessionEdit\n operation: Omit<MoveOperation, 'operationId'>\n sortKey: string\n}\n\nexport interface MovePlanContext {\n movePlan: MovePlan | null\n intentsByEdit: Map<SessionEdit, MoveIntent>\n noopMoveCount: number\n}\n\nfunction buildMoveEntries(edits: SessionEdit[]): {\n entries: MovePlanEntry[]\n noopMoveCount: number\n} {\n const entries: MovePlanEntry[] = []\n let noopMoveCount = 0\n\n for (const edit of edits) {\n const move = edit.move\n if (!move) continue\n\n const subject = buildAnchorRef(\n getElementDisplayName(edit.element) || edit.locator.tagName,\n edit.locator.domSelector,\n edit.locator.domSource,\n )\n const fromParent = buildAnchorRef(move.fromParentName, move.fromParentSelector, move.fromParentSource)\n const toParent = buildAnchorRef(move.toParentName, move.toParentSelector, move.toParentSource)\n const fromPlacement = buildPlacementFromMove(\n move.fromSiblingBefore,\n move.fromSiblingBeforeSelector,\n move.fromSiblingBeforeSource,\n move.fromSiblingAfter,\n move.fromSiblingAfterSelector,\n move.fromSiblingAfterSource,\n )\n const toPlacement = buildPlacementFromMove(\n move.toSiblingBefore,\n move.toSiblingBeforeSelector,\n move.toSiblingBeforeSource,\n move.toSiblingAfter,\n move.toSiblingAfterSelector,\n move.toSiblingAfterSource,\n )\n\n const reasons: string[] = []\n const classification = classifyMove(move)\n if (classification === 'noop') {\n noopMoveCount++\n continue\n }\n\n const interactionMode = move.mode ?? 'free'\n const visualDelta = toRoundedVisualDelta(move)\n if (visualDelta) {\n reasons.push(`Non-zero visual delta detected (${visualDelta.x}px, ${visualDelta.y}px).`)\n }\n\n const structuralChange = hasStructuralChange(move)\n if (structuralChange) reasons.push('Anchor placement changed between source and target.')\n else reasons.push('No anchor placement change; treating movement as layout intent translation.')\n\n const operationBase: Omit<MoveOperation, 'operationId'> = {\n classification,\n interactionMode,\n subject,\n from: { parent: fromParent, placement: fromPlacement },\n to: { parent: toParent, placement: toPlacement },\n ...(visualDelta ? { visualDelta } : {}),\n confidence: classification === 'existing_layout_move'\n ? 'high'\n : structuralChange\n ? 'medium'\n : 'high',\n reasons,\n }\n\n if (classification === 'layout_refactor') {\n operationBase.layoutPrescription = inferLayoutPrescription(edit, operationBase, reasons)\n }\n\n const sortSource = subject.source?.file\n ? `${subject.source.file}:${subject.source.line ?? 0}:${subject.source.column ?? 0}`\n : ''\n const sortKey = [\n sortSource,\n anchorKey(subject),\n anchorKey(toParent),\n toPlacement.description,\n ].join('|')\n entries.push({ edit, operation: operationBase, sortKey })\n }\n\n entries.sort((a, b) => a.sortKey.localeCompare(b.sortKey))\n return { entries, noopMoveCount }\n}\n\nexport function buildMovePlanContext(\n edits: SessionEdit[],\n _domContext?: unknown\n): MovePlanContext {\n const { entries, noopMoveCount } = buildMoveEntries(edits)\n if (entries.length === 0) {\n return {\n movePlan: null,\n intentsByEdit: new Map(),\n noopMoveCount,\n }\n }\n\n const operations: MoveOperation[] = []\n const intentsByEdit = new Map<SessionEdit, MoveIntent>()\n for (let i = 0; i < entries.length; i++) {\n const operationId = `op-${i + 1}`\n const operation: MoveOperation = { operationId, ...entries[i].operation }\n operations.push(operation)\n intentsByEdit.set(entries[i].edit, operation)\n }\n\n const affectedContainerMap = new Map<string, AnchorRef>()\n for (const operation of operations) {\n affectedContainerMap.set(anchorKey(operation.from.parent), operation.from.parent)\n affectedContainerMap.set(anchorKey(operation.to.parent), operation.to.parent)\n }\n\n const orderingConstraints = operations\n .filter(op => op.classification === 'existing_layout_move')\n .map(op => `${op.operationId}: place ${formatAnchorRef(op.subject)} ${op.to.placement.description} in ${formatAnchorRef(op.to.parent)}.`)\n\n const notes: string[] = []\n if (noopMoveCount > 0) notes.push(`Excluded ${noopMoveCount} no-op move(s).`)\n if (operations.some(op => op.classification === 'layout_refactor')) {\n notes.push('Layout refactor operations include best-practice flex/grid prescriptions.')\n }\n\n return {\n movePlan: {\n operations,\n affectedContainers: Array.from(affectedContainerMap.values()),\n orderingConstraints,\n notes,\n },\n intentsByEdit,\n noopMoveCount,\n }\n}\n\nexport function buildMovePlan(edits: SessionEdit[], domContext?: unknown): MovePlan {\n const context = buildMovePlanContext(edits, domContext)\n return context.movePlan ?? {\n operations: [],\n affectedContainers: [],\n orderingConstraints: [],\n notes: context.noopMoveCount > 0 ? [`Excluded ${context.noopMoveCount} no-op move(s).`] : [],\n }\n}\n\nexport function getMoveIntentForEdit(\n edit: SessionEdit,\n context?: MovePlanContext | null\n): MoveIntent | null {\n if (!edit.move) return null\n if (context?.intentsByEdit.has(edit)) return context.intentsByEdit.get(edit) ?? null\n const singleContext = buildMovePlanContext([edit])\n return singleContext.intentsByEdit.get(edit) ?? null\n}\n\nfunction buildMoveInstructionFromIntent(intent: MoveIntent): string {\n if (intent.classification === 'existing_layout_move') {\n return `Apply as a structural move in code: place ${formatAnchorRef(intent.subject)} ${intent.to.placement.description} in ${formatAnchorRef(intent.to.parent)}.`\n }\n const system = intent.layoutPrescription?.recommendedSystem ?? 'flex'\n return `Treat this as a ${system} layout refactor. Implement the listed structure/style steps in source code instead of drag replay.`\n}\n\nfunction formatMoveType(classification: MoveClassification): 'structural_move' | 'layout_refactor' {\n return classification === 'existing_layout_move' ? 'structural_move' : 'layout_refactor'\n}\n\nfunction buildMoveExportLines(intent: MoveIntent): string[] {\n const moveType = formatMoveType(intent.classification)\n const implementationSteps: string[] = []\n if (intent.classification === 'existing_layout_move') {\n implementationSteps.push(`Reorder/reparent ${formatAnchorRef(intent.subject)} to ${intent.to.placement.description} in ${formatAnchorRef(intent.to.parent)}.`)\n } else {\n const prescription = intent.layoutPrescription\n if (prescription) {\n implementationSteps.push(...prescription.refactorSteps)\n implementationSteps.push(...prescription.styleSteps)\n implementationSteps.push(...prescription.itemSteps)\n }\n }\n\n const lines: string[] = [\n 'moved:',\n `id: ${intent.operationId}`,\n `type: ${moveType}`,\n `subject: ${formatAnchorRef(intent.subject, '(unknown)')}`,\n `parent: ${formatAnchorRef(intent.to.parent, '(unknown)')}`,\n `current_anchor: ${intent.from.placement.description}`,\n `target_anchor: ${intent.to.placement.description}`,\n ...(intent.visualDelta\n ? [`visual_hint: ${intent.visualDelta.x}px horizontal, ${intent.visualDelta.y}px vertical`]\n : []),\n ]\n\n if (intent.layoutPrescription) {\n lines.push(`recommended_layout: ${intent.layoutPrescription.recommendedSystem}`)\n }\n\n lines.push('implementation_steps:')\n for (const step of implementationSteps) {\n lines.push(` - ${step}`)\n }\n\n lines.push('guardrails:')\n lines.push(' - Do not simulate movement with absolute positioning, left/top offsets, transform, or margin hacks.')\n lines.push(`instruction: ${buildMoveInstructionFromIntent(intent)}`)\n return lines\n}\n\ninterface SessionExportOptions {\n movePlanContext?: MovePlanContext | null\n includeMovePlanHeader?: boolean\n}\n\nexport interface ExportContentProfile {\n hasCssEdits: boolean\n hasTextEdits: boolean\n hasMoves: boolean\n hasComments: boolean\n}\n\nexport function getExportContentProfile(\n edits: SessionEdit[],\n comments: Comment[],\n movePlanOrContext?: MovePlan | MovePlanContext | null\n): ExportContentProfile {\n const moveOpCount = movePlanOrContext\n ? ('operations' in movePlanOrContext\n ? movePlanOrContext.operations.length\n : (movePlanOrContext.movePlan?.operations.length ?? 0))\n : (buildMovePlanContext(edits).movePlan?.operations.length ?? 0)\n\n return {\n hasCssEdits: edits.some(e => Object.keys(e.pendingStyles).length > 0),\n hasTextEdits: edits.some(e => e.textEdit != null),\n hasMoves: moveOpCount > 0,\n hasComments: comments.length > 0,\n }\n}\n\nexport function buildExportInstruction(profile: ExportContentProfile): string {\n const { hasCssEdits, hasTextEdits, hasMoves, hasComments } = profile\n\n if (!hasCssEdits && !hasTextEdits && !hasMoves && !hasComments) return ''\n\n if (!hasCssEdits && !hasTextEdits && !hasMoves) {\n return hasComments\n ? 'Address this feedback on the UI. Use the provided source location and selector to find each element in the codebase.'\n : ''\n }\n\n const parts: string[] = []\n if (hasCssEdits) parts.push('Apply the CSS changes to the targeted elements using the project\\'s existing styling approach (Tailwind, CSS modules, etc.). Map values to existing CSS variables, design tokens, or utility classes already used in the project whenever possible.')\n if (hasTextEdits) parts.push('Update the text content as specified.')\n if (hasMoves) parts.push('Implement the move plan below directly in source code. For `structural_move`, reorder/reparent elements using the target anchors. For `layout_refactor`, apply the listed flex/grid refactor steps. Do NOT simulate movement with absolute positioning, left/top offsets, transform, or margin hacks.')\n if (hasComments) parts.push('Address the comments on the relevant elements.')\n\n return `${parts.join(' ')} Use the provided source locations, selectors, and context HTML to locate each element in the codebase.`\n}\n\nexport function buildSessionExport(\n edits: SessionEdit[],\n comments: Comment[] = [],\n options?: SessionExportOptions\n): string {\n const blocks: string[] = []\n const planContext = options?.movePlanContext ?? buildMovePlanContext(edits)\n const movePlan = planContext.movePlan\n const includeMovePlanHeader = options?.includeMovePlanHeader !== false\n\n if (includeMovePlanHeader && movePlan && movePlan.operations.length > 0) {\n const planLines: string[] = [\n '=== LAYOUT MOVE PLAN ===',\n `operations: ${movePlan.operations.length}`,\n ]\n if (movePlan.affectedContainers.length > 0) {\n planLines.push('containers:')\n for (const container of movePlan.affectedContainers) {\n planLines.push(` - ${formatAnchorRef(container, '(unknown)')}`)\n }\n }\n if (movePlan.orderingConstraints.length > 0) {\n planLines.push('structural_constraints:')\n for (const constraint of movePlan.orderingConstraints) {\n planLines.push(` - ${constraint}`)\n }\n }\n if (movePlan.notes.length > 0) {\n planLines.push('plan_notes:')\n for (const note of movePlan.notes) {\n planLines.push(` - ${note}`)\n }\n }\n blocks.push(planLines.join('\\n'))\n }\n\n for (const edit of edits) {\n const moveIntent = getMoveIntentForEdit(edit, planContext)\n const hasMove = Boolean(moveIntent)\n const hasStyleOrText = Object.keys(edit.pendingStyles).length > 0 || edit.textEdit != null\n if (!hasMove && !hasStyleOrText) continue\n\n const block = hasMove\n ? buildEditExportWithOptions(edit.locator, edit.pendingStyles, edit.textEdit, { skipContext: true })\n : buildEditExport(edit.locator, edit.pendingStyles, edit.textEdit)\n\n let moveBlock = ''\n if (moveIntent) {\n moveBlock = `\\n${buildMoveExportLines(moveIntent).join('\\n')}`\n }\n blocks.push(block + moveBlock)\n }\n\n for (const comment of comments) {\n blocks.push(buildCommentExport(comment.locator, comment.text, comment.replies))\n }\n\n return blocks.join('\\n\\n---\\n\\n')\n}\n\nexport type {\n ElementInfo,\n CSSPropertyValue,\n SpacingProperties,\n BorderRadiusProperties,\n BorderStyle,\n BorderProperties,\n FlexProperties,\n DirectEditState,\n SpacingPropertyKey,\n BorderRadiusPropertyKey,\n BorderPropertyKey,\n FlexPropertyKey,\n MeasurementLine,\n MeasurementState,\n ColorValue,\n ColorProperties,\n ColorPropertyKey,\n SizingProperties,\n SizingPropertyKey,\n SizingMode,\n SizingValue,\n TypographyProperties,\n TypographyPropertyKey,\n ReactComponentFrame,\n ElementLocator,\n DragState,\n DropTarget,\n DropIndicator,\n} from './types'\n","import type { CSSPropertyValue } from '../types'\n\nexport function parsePropertyValue(value: string): CSSPropertyValue {\n const raw = value.trim()\n const match = raw.match(/^(-?\\d*\\.?\\d+)(px|rem|em|vh|vw|%)?$/)\n\n if (match) {\n return {\n numericValue: parseFloat(match[1]),\n unit: (match[2] as CSSPropertyValue['unit']) || 'px',\n raw,\n }\n }\n\n return {\n numericValue: 0,\n unit: 'px',\n raw,\n }\n}\n\nexport function formatPropertyValue(value: CSSPropertyValue): string {\n if (value.raw === 'auto' || value.raw === 'inherit' || value.raw === 'initial') {\n return value.raw\n }\n return `${value.numericValue}${value.unit}`\n}\n","import { useSyncExternalStore } from 'react'\n\ntype CanvasSnapshot = { active: boolean; zoom: number; panX: number; panY: number }\n\nconst DEFAULT: CanvasSnapshot = { active: false, zoom: 1, panX: 0, panY: 0 }\n\nlet snapshot: CanvasSnapshot = DEFAULT\nconst listeners = new Set<() => void>()\nlet ownerCount = 0\n\nlet bodyOffset = { x: 0, y: 0 }\nexport function getBodyOffset() { return bodyOffset }\nexport function setBodyOffset(o: { x: number; y: number }) { bodyOffset = o }\n\nexport function getCanvasSnapshot(): CanvasSnapshot {\n return snapshot\n}\n\nexport function setCanvasSnapshot(next: CanvasSnapshot) {\n snapshot = next\n listeners.forEach((cb) => cb())\n}\n\nexport function registerCanvasStoreOwner(): () => void {\n ownerCount += 1\n if (ownerCount > 1 && (typeof process === 'undefined' || process.env.NODE_ENV !== 'test')) {\n console.warn('[made-refine] multiple DirectEditProvider instances share canvas-store globals')\n }\n return () => {\n ownerCount = Math.max(0, ownerCount - 1)\n }\n}\n\nfunction subscribe(cb: () => void) {\n listeners.add(cb)\n return () => {\n listeners.delete(cb)\n }\n}\n\n/** Synchronous canvas state — no rAF lag. Use for overlays that must track the DOM transform exactly. */\nexport function useCanvasSnapshot(): CanvasSnapshot {\n return useSyncExternalStore(subscribe, getCanvasSnapshot, () => DEFAULT)\n}\n","import type { ElementInfo, MeasurementLine, Guideline } from '../types'\nimport { isTextElement } from './element-selection'\nimport { getCanvasSnapshot, getBodyOffset } from '../canvas-store'\n\nexport function getZoomScale(): number {\n const snap = getCanvasSnapshot()\n return snap.active ? snap.zoom : 1\n}\n\nexport function getElementInfo(element: HTMLElement): ElementInfo {\n const computed = window.getComputedStyle(element)\n const parentElement = element.parentElement\n\n const isFlexContainer = computed.display === 'flex' || computed.display === 'inline-flex'\n\n let isFlexItem = false\n if (parentElement) {\n const parentComputed = window.getComputedStyle(parentElement)\n isFlexItem = parentComputed.display === 'flex' || parentComputed.display === 'inline-flex'\n }\n\n return {\n tagName: element.tagName.toLowerCase(),\n id: element.id || null,\n classList: Array.from(element.classList),\n isFlexContainer,\n isFlexItem,\n isTextElement: isTextElement(element),\n parentElement,\n hasChildren: element.children.length > 0,\n }\n}\n\ninterface DimensionDisplay {\n width: string\n height: string\n}\n\nfunction isFitSizing(element: HTMLElement, dimension: 'width' | 'height'): boolean {\n const computed = window.getComputedStyle(element)\n const inlineValue = element.style[dimension]\n\n if (inlineValue === 'auto') return true\n\n const computedValue = computed[dimension]\n\n if (!inlineValue) {\n const parent = element.parentElement\n if (parent) {\n const parentComputed = window.getComputedStyle(parent)\n if (parentComputed.display === 'flex' || parentComputed.display === 'inline-flex') {\n const flexBasis = computed.flexBasis\n const flexGrow = computed.flexGrow\n if (flexBasis === 'auto' && flexGrow === '0') {\n return true\n }\n }\n }\n\n if (dimension === 'width') {\n if (computed.display === 'block' && !inlineValue) {\n return false\n }\n if (\n computed.display === 'inline-block' ||\n computed.display === 'inline-flex' ||\n computed.display === 'inline'\n ) {\n return true\n }\n }\n\n if (dimension === 'height') {\n return !inlineValue\n }\n }\n\n if (computedValue.includes('fit-content') || computedValue.includes('max-content')) {\n return true\n }\n\n return false\n}\n\nexport function getDimensionDisplay(element: HTMLElement): DimensionDisplay {\n const width = Math.round(element.offsetWidth)\n const height = Math.round(element.offsetHeight)\n\n const widthIsFit = isFitSizing(element, 'width')\n const heightIsFit = isFitSizing(element, 'height')\n\n return {\n width: widthIsFit ? `Fit ${width}` : `${width}`,\n height: heightIsFit ? `Fit ${height}` : `${height}`,\n }\n}\n\n\nexport function calculateParentMeasurements(element: HTMLElement, container?: HTMLElement): MeasurementLine[] {\n const parent = container ?? element.parentElement\n if (!parent) return []\n\n const elementRect = element.getBoundingClientRect()\n const parentRect = parent.getBoundingClientRect()\n\n // Use clientLeft/clientTop for reliable border widths, clientWidth/clientHeight\n // for inner dimensions (handles scrollbars correctly)\n const paddingBoxLeft = parentRect.left + parent.clientLeft\n const paddingBoxTop = parentRect.top + parent.clientTop\n const paddingBoxRight = parentRect.left + parent.clientLeft + parent.clientWidth\n const paddingBoxBottom = parentRect.top + parent.clientTop + parent.clientHeight\n\n let parentInnerLeft: number\n let parentInnerTop: number\n let parentInnerRight: number\n let parentInnerBottom: number\n\n if (container) {\n // Ancestor case: measure from padding-box (inside border, outside padding).\n // The ancestor's padding doesn't directly position the child — intermediate\n // elements do — so the visually correct edge is inside the border only.\n parentInnerLeft = paddingBoxLeft\n parentInnerTop = paddingBoxTop\n parentInnerRight = paddingBoxRight\n parentInnerBottom = paddingBoxBottom\n } else {\n // Direct parent case: measure from content-box (inside border and padding).\n // The parent's padding IS the gap between its edge and the child's layout area.\n const parentStyles = window.getComputedStyle(parent)\n parentInnerLeft = paddingBoxLeft + (parseFloat(parentStyles.paddingLeft) || 0)\n parentInnerTop = paddingBoxTop + (parseFloat(parentStyles.paddingTop) || 0)\n parentInnerRight = paddingBoxRight - (parseFloat(parentStyles.paddingRight) || 0)\n parentInnerBottom = paddingBoxBottom - (parseFloat(parentStyles.paddingBottom) || 0)\n }\n\n const zoom = getZoomScale()\n const measurements: MeasurementLine[] = []\n\n const topDistance = Math.round((elementRect.top - parentInnerTop) / zoom)\n if (topDistance > 0) {\n const midX = elementRect.left + elementRect.width / 2\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: parentInnerTop,\n x2: midX,\n y2: elementRect.top,\n distance: topDistance,\n labelPosition: { x: midX, y: (parentInnerTop + elementRect.top) / 2 },\n })\n }\n\n const bottomDistance = Math.round((parentInnerBottom - elementRect.bottom) / zoom)\n if (bottomDistance > 0) {\n const midX = elementRect.left + elementRect.width / 2\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: elementRect.bottom,\n x2: midX,\n y2: parentInnerBottom,\n distance: bottomDistance,\n labelPosition: { x: midX, y: (elementRect.bottom + parentInnerBottom) / 2 },\n })\n }\n\n const leftDistance = Math.round((elementRect.left - parentInnerLeft) / zoom)\n if (leftDistance > 0) {\n const midY = elementRect.top + elementRect.height / 2\n measurements.push({\n direction: 'horizontal',\n x1: parentInnerLeft,\n y1: midY,\n x2: elementRect.left,\n y2: midY,\n distance: leftDistance,\n labelPosition: { x: (parentInnerLeft + elementRect.left) / 2, y: midY },\n })\n }\n\n const rightDistance = Math.round((parentInnerRight - elementRect.right) / zoom)\n if (rightDistance > 0) {\n const midY = elementRect.top + elementRect.height / 2\n measurements.push({\n direction: 'horizontal',\n x1: elementRect.right,\n y1: midY,\n x2: parentInnerRight,\n y2: midY,\n distance: rightDistance,\n labelPosition: { x: (elementRect.right + parentInnerRight) / 2, y: midY },\n })\n }\n\n return measurements\n}\n\nexport function calculateElementMeasurements(\n from: HTMLElement,\n to: HTMLElement\n): MeasurementLine[] {\n const fromRect = from.getBoundingClientRect()\n const toRect = to.getBoundingClientRect()\n const zoom = getZoomScale()\n const measurements: MeasurementLine[] = []\n\n const horizontalOverlap =\n fromRect.left < toRect.right && fromRect.right > toRect.left\n const verticalOverlap =\n fromRect.top < toRect.bottom && fromRect.bottom > toRect.top\n\n if (verticalOverlap) {\n const overlapTop = Math.max(fromRect.top, toRect.top)\n const overlapBottom = Math.min(fromRect.bottom, toRect.bottom)\n const midY = (overlapTop + overlapBottom) / 2\n\n if (fromRect.right <= toRect.left) {\n const distance = Math.round((toRect.left - fromRect.right) / zoom)\n measurements.push({\n direction: 'horizontal',\n x1: fromRect.right,\n y1: midY,\n x2: toRect.left,\n y2: midY,\n distance,\n labelPosition: { x: (fromRect.right + toRect.left) / 2, y: midY },\n })\n } else if (fromRect.left >= toRect.right) {\n const distance = Math.round((fromRect.left - toRect.right) / zoom)\n measurements.push({\n direction: 'horizontal',\n x1: toRect.right,\n y1: midY,\n x2: fromRect.left,\n y2: midY,\n distance,\n labelPosition: { x: (toRect.right + fromRect.left) / 2, y: midY },\n })\n }\n }\n\n if (horizontalOverlap) {\n const overlapLeft = Math.max(fromRect.left, toRect.left)\n const overlapRight = Math.min(fromRect.right, toRect.right)\n const midX = (overlapLeft + overlapRight) / 2\n\n if (fromRect.bottom <= toRect.top) {\n const distance = Math.round((toRect.top - fromRect.bottom) / zoom)\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: fromRect.bottom,\n x2: midX,\n y2: toRect.top,\n distance,\n labelPosition: { x: midX, y: (fromRect.bottom + toRect.top) / 2 },\n })\n } else if (fromRect.top >= toRect.bottom) {\n const distance = Math.round((fromRect.top - toRect.bottom) / zoom)\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: toRect.bottom,\n x2: midX,\n y2: fromRect.top,\n distance,\n labelPosition: { x: midX, y: (toRect.bottom + fromRect.top) / 2 },\n })\n }\n }\n\n if (!horizontalOverlap && !verticalOverlap) {\n const fromCenterX = fromRect.left + fromRect.width / 2\n const fromCenterY = fromRect.top + fromRect.height / 2\n const toCenterX = toRect.left + toRect.width / 2\n const toCenterY = toRect.top + toRect.height / 2\n\n const hDistance = toCenterX > fromCenterX\n ? Math.round((toRect.left - fromRect.right) / zoom)\n : Math.round((fromRect.left - toRect.right) / zoom)\n\n if (hDistance > 0) {\n const startX = toCenterX > fromCenterX ? fromRect.right : fromRect.left\n const endX = toCenterX > fromCenterX ? toRect.left : toRect.right\n const y = (fromCenterY + toCenterY) / 2\n measurements.push({\n direction: 'horizontal',\n x1: startX,\n y1: y,\n x2: endX,\n y2: y,\n distance: hDistance,\n labelPosition: { x: (startX + endX) / 2, y },\n })\n }\n\n const vDistance = toCenterY > fromCenterY\n ? Math.round((toRect.top - fromRect.bottom) / zoom)\n : Math.round((fromRect.top - toRect.bottom) / zoom)\n\n if (vDistance > 0) {\n const x = (fromCenterX + toCenterX) / 2\n const startY = toCenterY > fromCenterY ? fromRect.bottom : fromRect.top\n const endY = toCenterY > fromCenterY ? toRect.top : toRect.bottom\n measurements.push({\n direction: 'vertical',\n x1: x,\n y1: startY,\n x2: x,\n y2: endY,\n distance: vDistance,\n labelPosition: { x, y: (startY + endY) / 2 },\n })\n }\n }\n\n return measurements\n}\n\nconst GUIDELINE_PROXIMITY = 80\n\nexport function calculateGuidelineMeasurements(\n element: HTMLElement,\n guidelines: Guideline[],\n mousePosition?: { x: number; y: number } | null,\n): MeasurementLine[] {\n if (guidelines.length === 0) return []\n\n const snap = getCanvasSnapshot()\n const zoom = snap.active ? snap.zoom : 1\n const rect = element.getBoundingClientRect()\n const measurements: MeasurementLine[] = []\n\n for (const g of guidelines) {\n let viewportPos: number\n if (snap.active) {\n const pan = g.orientation === 'horizontal' ? snap.panY : snap.panX\n const bo = g.orientation === 'horizontal' ? getBodyOffset().y : getBodyOffset().x\n viewportPos = bo + (g.position - bo + pan) * zoom\n } else {\n const scroll = g.orientation === 'horizontal' ? window.scrollY : window.scrollX\n viewportPos = g.position - scroll\n }\n\n if (g.orientation === 'horizontal') {\n const midX = rect.left + rect.width / 2\n\n if (mousePosition && Math.abs(mousePosition.y - viewportPos) > GUIDELINE_PROXIMITY) continue\n\n if (viewportPos < rect.top) {\n const distance = Math.round((rect.top - viewportPos) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: viewportPos,\n x2: midX,\n y2: rect.top,\n distance,\n labelPosition: { x: midX, y: (viewportPos + rect.top) / 2 },\n })\n }\n } else if (viewportPos > rect.bottom) {\n const distance = Math.round((viewportPos - rect.bottom) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'vertical',\n x1: midX,\n y1: rect.bottom,\n x2: midX,\n y2: viewportPos,\n distance,\n labelPosition: { x: midX, y: (rect.bottom + viewportPos) / 2 },\n })\n }\n }\n } else {\n const midY = rect.top + rect.height / 2\n\n if (mousePosition && Math.abs(mousePosition.x - viewportPos) > GUIDELINE_PROXIMITY) continue\n\n if (viewportPos < rect.left) {\n const distance = Math.round((rect.left - viewportPos) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'horizontal',\n x1: viewportPos,\n y1: midY,\n x2: rect.left,\n y2: midY,\n distance,\n labelPosition: { x: (viewportPos + rect.left) / 2, y: midY },\n })\n }\n } else if (viewportPos > rect.right) {\n const distance = Math.round((viewportPos - rect.right) / zoom)\n if (distance > 0) {\n measurements.push({\n direction: 'horizontal',\n x1: rect.right,\n y1: midY,\n x2: viewportPos,\n y2: midY,\n distance,\n labelPosition: { x: (rect.right + viewportPos) / 2, y: midY },\n })\n }\n }\n }\n }\n\n return measurements\n}\n","import type { ReactComponentFrame, DomSourceLocation } from '../types'\n\ndeclare global {\n interface Window {\n __DIRECT_EDIT_DEVTOOLS__?: {\n getFiberForElement: (element: HTMLElement) => unknown | null\n hasHook?: boolean\n }\n }\n}\n\n// Accesses React fiber internals to find the component stack. This is an undocumented\n// API that could change between React versions, but is a common pattern for dev tools.\n// Returns an empty array gracefully if React internals are unavailable.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getFiberForElement(element: HTMLElement): any | null {\n if (typeof window !== 'undefined') {\n const devtools = window.__DIRECT_EDIT_DEVTOOLS__\n if (devtools?.getFiberForElement) {\n const fiber = devtools.getFiberForElement(element)\n if (fiber) return fiber as any\n }\n }\n\n const fiberKey = Object.keys(element).find(\n (key) => key.startsWith('__reactFiber$') || key.startsWith('__reactInternalInstance$')\n )\n\n if (!fiberKey) return null\n return (element as any)[fiberKey] || null\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getSourceFromFiber(fiber: any):\n | {\n fileName?: string\n lineNumber?: number\n columnNumber?: number\n }\n | null {\n const debugSource = fiber?._debugSource\n if (debugSource?.fileName) return debugSource\n\n const owner = fiber?._debugOwner\n const ownerPending = owner?.pendingProps?.__source\n if (ownerPending?.fileName) return ownerPending\n\n const ownerMemo = owner?.memoizedProps?.__source\n if (ownerMemo?.fileName) return ownerMemo\n\n const pending = fiber?.pendingProps?.__source\n if (pending?.fileName) return pending\n\n const memo = fiber?.memoizedProps?.__source\n if (memo?.fileName) return memo\n\n return null\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction buildFrame(fiber: any): ReactComponentFrame | null {\n const type = fiber?.type\n if (typeof type !== 'function' && typeof type !== 'object') return null\n\n const name = type?.displayName || type?.name || null\n if (!name || name === 'Fragment') return null\n\n const frame: ReactComponentFrame = { name }\n const source = getSourceFromFiber(fiber)\n if (source?.fileName) {\n frame.file = source.fileName\n if (typeof source.lineNumber === 'number') {\n frame.line = source.lineNumber\n }\n if (typeof source.columnNumber === 'number') {\n frame.column = source.columnNumber\n }\n }\n\n return frame\n}\n\nfunction shouldIncludeFrame(\n frame: ReactComponentFrame,\n lastFrame: ReactComponentFrame | null\n): boolean {\n if (!lastFrame) return true\n if (frame.name !== lastFrame.name) return true\n if (!lastFrame.file && frame.file) return true\n if (lastFrame.file && frame.file && lastFrame.line == null && frame.line != null) return true\n if (\n lastFrame.file &&\n frame.file &&\n lastFrame.line != null &&\n frame.line != null &&\n lastFrame.column == null &&\n frame.column != null\n ) {\n return true\n }\n return false\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getOwnerStack(fiber: any): { frames: ReactComponentFrame[]; nearestComponentFiber: any | null } {\n const frames: ReactComponentFrame[] = []\n let current = fiber\n let lastFrame: ReactComponentFrame | null = null\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let nearestComponentFiber: any | null = null\n\n while (current) {\n const frame = buildFrame(current)\n if (frame && shouldIncludeFrame(frame, lastFrame)) {\n frames.push(frame)\n lastFrame = frame\n if (!nearestComponentFiber) {\n nearestComponentFiber = current\n }\n }\n current = current._debugOwner\n }\n\n return { frames, nearestComponentFiber }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getRenderStack(fiber: any): { frames: ReactComponentFrame[]; nearestComponentFiber: any | null } {\n const frames: ReactComponentFrame[] = []\n let current = fiber\n let lastFrame: ReactComponentFrame | null = null\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let nearestComponentFiber: any | null = null\n\n while (current) {\n const frame = buildFrame(current)\n if (frame && shouldIncludeFrame(frame, lastFrame)) {\n frames.push(frame)\n lastFrame = frame\n if (!nearestComponentFiber) {\n nearestComponentFiber = current\n }\n }\n current = current.return\n }\n\n return { frames, nearestComponentFiber }\n}\n\nexport interface ReactComponentInfo {\n frames: ReactComponentFrame[]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n nearestComponentFiber: any | null\n /** Source file of the host element's own fiber (_debugSource) — points to the component definition file */\n elementSourceFile?: string\n}\n\nexport function getReactComponentInfo(element: HTMLElement): ReactComponentInfo {\n const fiber = getFiberForElement(element)\n if (!fiber) return { frames: [], nearestComponentFiber: null }\n\n const elementSource = getSourceFromFiber(fiber)\n const elementSourceFile = elementSource?.fileName || undefined\n\n const ownerResult = getOwnerStack(fiber)\n if (ownerResult.frames.length > 0) {\n return { ...ownerResult, elementSourceFile }\n }\n\n return { ...getRenderStack(fiber), elementSourceFile }\n}\n\nexport function getReactComponentStack(element: HTMLElement): ReactComponentFrame[] {\n return getReactComponentInfo(element).frames\n}\n\n// --- Component props extraction ---\n\nconst EXCLUDED_PROP_KEYS = new Set([\n 'className', 'style', 'children', 'ref', 'key', 'render',\n])\n\nfunction serializePropValue(value: unknown): unknown {\n if (typeof value === 'function') return '[function]'\n if (typeof value === 'symbol') return undefined\n if (value === undefined) return undefined\n if (value !== null && typeof value === 'object') {\n // React elements have $$typeof\n if ('$$typeof' in value) return '[element]'\n try {\n JSON.stringify(value)\n return value\n } catch {\n return '[object]'\n }\n }\n return value\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getComponentProps(fiber: any): Record<string, unknown> {\n const props = fiber?.memoizedProps ?? fiber?.pendingProps\n if (!props || typeof props !== 'object') return {}\n\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(props)) {\n if (EXCLUDED_PROP_KEYS.has(key)) continue\n if (key.startsWith('data-')) continue\n const serialized = serializePropValue(value)\n if (serialized !== undefined) {\n result[key] = serialized\n }\n }\n return result\n}\n\n// --- Source location helpers ---\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getCallSiteSource(fiber: any): DomSourceLocation | null {\n const source = fiber?._debugSource\n if (source?.fileName) {\n return {\n file: source.fileName,\n line: typeof source.lineNumber === 'number' ? source.lineNumber : undefined,\n column: typeof source.columnNumber === 'number' ? source.columnNumber : undefined,\n }\n }\n const pending = fiber?.pendingProps?.__source\n if (pending?.fileName) {\n return {\n file: pending.fileName,\n line: typeof pending.lineNumber === 'number' ? pending.lineNumber : undefined,\n column: typeof pending.columnNumber === 'number' ? pending.columnNumber : undefined,\n }\n }\n return null\n}\n\nexport function deriveDefinitionSource(\n frames: ReactComponentFrame[],\n): DomSourceLocation | null {\n for (const frame of frames) {\n if (frame.file && isComponentPrimitivePath(frame.file)) {\n return { file: frame.file, line: frame.line, column: frame.column }\n }\n }\n return null\n}\n\n// --- Component primitive classification ---\n\nconst PRIMITIVE_PATH_PATTERNS = [\n /\\/components\\/ui\\//,\n /\\/ui\\/primitives\\//,\n /\\/design-system\\//,\n]\n\nconst PRIMITIVE_NPM_PATTERNS = [\n /@base-ui\\//,\n /@radix-ui\\//,\n /@headlessui\\//,\n /@chakra-ui\\//,\n /@mantine\\//,\n /@mui\\//,\n /@ark-ui\\//,\n]\n\n// Match only top-level framework packages (e.g., node_modules/react/ but not @base-ui/react/)\nconst FRAMEWORK_EXCLUSION_PATTERNS = [\n /node_modules\\/react\\//,\n /node_modules\\/react-dom\\//,\n /node_modules\\/next\\/dist\\//,\n /node_modules\\/scheduler\\//,\n /node_modules\\/react-server\\//,\n]\n\nexport function isComponentPrimitivePath(filePath: string): boolean {\n const normalized = filePath.replace(/\\\\/g, '/')\n\n for (const pattern of FRAMEWORK_EXCLUSION_PATTERNS) {\n if (pattern.test(normalized)) return false\n }\n\n // Check npm UI library patterns first (they're in node_modules)\n for (const pattern of PRIMITIVE_NPM_PATTERNS) {\n if (pattern.test(normalized)) return true\n }\n\n for (const pattern of PRIMITIVE_PATH_PATTERNS) {\n if (pattern.test(normalized)) return true\n }\n\n return false\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function classifyComponentFiber(fiber: any, frames: ReactComponentFrame[], elementSourceFile?: string): { isComponentPrimitive: boolean } {\n // Check the host element's own source first — for component primitives,\n // this points to the file where the component renders its host elements.\n // This check runs before the fiber null guard because elementSourceFile\n // comes from the host element's _debugSource, not the component fiber.\n if (elementSourceFile && isComponentPrimitivePath(elementSourceFile)) {\n return { isComponentPrimitive: true }\n }\n\n if (!fiber) return { isComponentPrimitive: false }\n\n const callSite = getCallSiteSource(fiber)\n if (callSite?.file && isComponentPrimitivePath(callSite.file)) {\n return { isComponentPrimitive: true }\n }\n\n for (const frame of frames) {\n if (frame.file && isComponentPrimitivePath(frame.file)) {\n return { isComponentPrimitive: true }\n }\n }\n\n // Fallback: detect pre-compiled npm package components.\n // If the host element has no _debugSource (elementSourceFile is undefined)\n // but the component fiber has _debugSource (called from dev-transformed user code),\n // the component renders pre-compiled JSX — typical of npm UI packages whose\n // source isn't processed by the React dev transform.\n if (!elementSourceFile && fiber._debugSource) {\n return { isComponentPrimitive: true }\n }\n\n return { isComponentPrimitive: false }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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