import { sectionName } from '@/components/stores/section-names'; /** What the merchant selected in the preview, sent with their next "Ask the AI" message. */ export type PreviewSelection = { /** The section's id in the design ("header" and "footer" for those). */ section: string; /** The section in plain words, such as "Hero" or "Products". */ label: string; /** What inside it, such as 'Heading "Quietly luxurious care"'. Null for the whole section. */ detail: string | null; }; type Found = { element: HTMLElement; id: string; type: string }; const GREEN = '#10b981'; const LAYER = '2147483646'; /** Moving further than this while holding the button draws a box instead of a click. */ const DRAG_START = 6; /** The section an element belongs to, or null for parts that are not sections (such as the WhatsApp button). */ function sectionOf(element: Element | null): Found | null { const band = element?.closest('[data-section]'); if (band) { return { element: band, id: band.dataset.section ?? '', type: band.dataset.sectionType ?? '', }; } const header = element?.closest('.sf-root header'); if (header) { return { element: header, id: 'header', type: 'header' }; } const footer = element?.closest('.sf-root footer'); if (footer) { return { element: footer, id: 'footer', type: 'footer' }; } return null; } function clip(text: string | null | undefined, length = 80): string { const clean = (text ?? '').replace(/\s+/g, ' ').trim(); return clean.length > length ? `${clean.slice(0, length - 1)}…` : clean; } /** Name one thing on the page in plain words, such as 'Button "Shop now"'. */ function describe(element: HTMLElement): string { const tag = element.tagName.toLowerCase(); if (tag === 'img') { const alt = clip((element as HTMLImageElement).alt, 60); return alt ? `Photo "${alt}"` : 'Photo'; } if (tag === 'video' || tag === 'iframe') { return 'Video'; } const text = clip(element.innerText || element.textContent); const kind = /^h[1-6]$/.test(tag) ? 'Heading' : tag === 'button' || element.getAttribute('role') === 'button' ? 'Button' : tag === 'a' ? 'Link' : 'Text'; return text ? `${kind} "${text}"` : kind; } const THING = 'img, video, iframe, h1, h2, h3, h4, h5, h6, button, a, p, li, blockquote, summary, dt, dd'; /** The meaningful thing under the pointer (a heading, photo, button…), inside its section. */ function thingAt(target: Element, section: HTMLElement): HTMLElement | null { const thing = target.closest(THING); return thing && section.contains(thing) && thing !== section ? thing : null; } function overlap(a: DOMRect, b: DOMRect): number { const width = Math.min(a.right, b.right) - Math.max(a.left, b.left); const height = Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top); return width > 0 && height > 0 ? width * height : 0; } function box( doc: Document, style: Partial, ): HTMLDivElement { const element = doc.createElement('div'); Object.assign( element.style, { position: 'fixed', pointerEvents: 'none', zIndex: LAYER, display: 'none', } satisfies Partial, style, ); doc.body.appendChild(element); return element; } function place( element: HTMLElement, rect: | DOMRect | { left: number; top: number; width: number; height: number }, ) { Object.assign(element.style, { display: 'block', left: `${rect.left}px`, top: `${rect.top}px`, width: `${rect.width}px`, height: `${rect.height}px`, }); } /** * Turn on "Select to edit" inside the preview. The merchant can: * - click one thing (a heading, photo, button…) to pick it and its section, or * - drag a box over an area: the section it covers most is picked, with the things inside the box. * A green outline shows what would be picked. Escape stops. Returns a function that stops it. */ export function startPicker( frame: HTMLIFrameElement, onPick: (selection: PreviewSelection) => void, onCancel: () => void, ): () => void { const doc = frame.contentDocument; const win = frame.contentWindow; if (!doc || !win || !doc.body) { return () => {}; } // A clear layer over the page catches the pointer, so links and buttons do not react. const shield = box(doc, { inset: '0', pointerEvents: 'auto', cursor: 'crosshair', background: 'transparent', zIndex: '2147483645', }); shield.style.display = 'block'; const outline = box(doc, { border: `2px solid ${GREEN}`, borderRadius: '8px', background: 'rgba(16, 185, 129, 0.08)', }); const area = box(doc, { border: `2px dashed ${GREEN}`, borderRadius: '6px', background: 'rgba(16, 185, 129, 0.12)', }); const tag = doc.createElement('span'); Object.assign(tag.style, { position: 'fixed', zIndex: '2147483647', pointerEvents: 'none', display: 'none', padding: '3px 9px', borderRadius: '999px', background: GREEN, color: '#fff', font: '600 12px/1.4 system-ui, sans-serif', whiteSpace: 'nowrap', maxWidth: '90vw', overflow: 'hidden', textOverflow: 'ellipsis', } satisfies Partial); doc.body.appendChild(tag); /** The page element under a point, looking through our own layer. */ const under = (x: number, y: number): Element | null => doc .elementsFromPoint(x, y) .find( (element) => element !== shield && element !== outline && element !== area && element !== tag, ) ?? null; const label = (text: string, rect: DOMRect) => { tag.textContent = text; tag.style.display = 'block'; tag.style.left = `${Math.max(rect.left, 4)}px`; tag.style.top = `${Math.max(rect.top - 26, 4)}px`; }; /** What a click at this point would pick. */ const atPoint = (x: number, y: number) => { const target = under(x, y); const section = sectionOf(target); if (!target || !section) { return null; } const thing = thingAt(target, section.element); return { section, thing }; }; /** What a box over this area would pick. */ const inArea = (rect: DOMRect) => { let best: Found | null = null; let most = 0; doc.querySelectorAll( '[data-section], .sf-root header, .sf-root footer', ).forEach((element) => { const found = sectionOf(element); const covered = overlap(rect, element.getBoundingClientRect()); if (found && found.element === element && covered > most) { best = found; most = covered; } }); if (!best) { return null; } const chosen: Found = best; const things = [...chosen.element.querySelectorAll(THING)] // Things mostly inside the box (at least 60%), so a rough box still catches them. .filter((element) => { const inside = element.getBoundingClientRect(); const size = inside.width * inside.height; return size > 0 && overlap(rect, inside) >= size * 0.6; }) // Skip things inside another picked thing, such as a link inside a list item. .filter( (element, _, all) => !all.some( (other) => other !== element && other.contains(element), ), ); return { section: chosen, things }; }; let start: { x: number; y: number } | null = null; let dragging = false; const areaRect = (x: number, y: number) => new DOMRect( Math.min(start!.x, x), Math.min(start!.y, y), Math.abs(x - start!.x), Math.abs(y - start!.y), ); const onMove = (event: PointerEvent) => { if ( start && !dragging && Math.hypot(event.clientX - start.x, event.clientY - start.y) > DRAG_START ) { dragging = true; } if (dragging) { const rect = areaRect(event.clientX, event.clientY); place(area, rect); const found = inArea(rect); if (found) { place(outline, found.section.element.getBoundingClientRect()); label( `${sectionName(found.section.type)} · area`, found.section.element.getBoundingClientRect(), ); } return; } const found = atPoint(event.clientX, event.clientY); if (!found) { outline.style.display = 'none'; tag.style.display = 'none'; return; } const shown = found.thing ?? found.section.element; const rect = shown.getBoundingClientRect(); place( outline, new DOMRect( rect.left - 3, rect.top - 3, rect.width + 6, rect.height + 6, ), ); label( found.thing ? `${sectionName(found.section.type)} › ${describe(found.thing).split(' "')[0]}` : sectionName(found.section.type), rect, ); }; const onDown = (event: PointerEvent) => { if (event.button !== 0) { return; } event.preventDefault(); start = { x: event.clientX, y: event.clientY }; dragging = false; // Keep getting the pointer even if it leaves the preview while drawing a box. try { shield.setPointerCapture(event.pointerId); } catch { // Not every pointer can be captured; drawing still works inside the preview. } }; const onUp = (event: PointerEvent) => { if (!start) { return; } if (dragging) { const found = inArea(areaRect(event.clientX, event.clientY)); start = null; dragging = false; area.style.display = 'none'; if (found) { const detail = found.things .slice(0, 4) .map(describe) .join(', '); onPick({ section: found.section.id, label: sectionName(found.section.type), detail: detail ? clip(`Area with: ${detail}`, 300) : null, }); } return; } start = null; const found = atPoint(event.clientX, event.clientY); if (found) { onPick({ section: found.section.id, label: sectionName(found.section.type), detail: found.thing ? describe(found.thing) : null, }); } }; const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') { onCancel(); } }; const onLeave = () => { if (!start) { outline.style.display = 'none'; tag.style.display = 'none'; } }; shield.addEventListener('pointermove', onMove); shield.addEventListener('pointerdown', onDown); shield.addEventListener('pointerup', onUp); shield.addEventListener('pointerleave', onLeave); doc.addEventListener('keydown', onKey); return () => { doc.removeEventListener('keydown', onKey); shield.remove(); outline.remove(); area.remove(); tag.remove(); }; }