AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

preview-picker.ts 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import { sectionName } from '@/components/stores/section-names';
  2. /** What the merchant selected in the preview, sent with their next "Ask the AI" message. */
  3. export type PreviewSelection = {
  4. /** The section's id in the design ("header" and "footer" for those). */
  5. section: string;
  6. /** The section in plain words, such as "Hero" or "Products". */
  7. label: string;
  8. /** What inside it, such as 'Heading "Quietly luxurious care"'. Null for the whole section. */
  9. detail: string | null;
  10. };
  11. type Found = { element: HTMLElement; id: string; type: string };
  12. const GREEN = '#10b981';
  13. const LAYER = '2147483646';
  14. /** Moving further than this while holding the button draws a box instead of a click. */
  15. const DRAG_START = 6;
  16. /** The section an element belongs to, or null for parts that are not sections (such as the WhatsApp button). */
  17. function sectionOf(element: Element | null): Found | null {
  18. const band = element?.closest<HTMLElement>('[data-section]');
  19. if (band) {
  20. return {
  21. element: band,
  22. id: band.dataset.section ?? '',
  23. type: band.dataset.sectionType ?? '',
  24. };
  25. }
  26. const header = element?.closest<HTMLElement>('.sf-root header');
  27. if (header) {
  28. return { element: header, id: 'header', type: 'header' };
  29. }
  30. const footer = element?.closest<HTMLElement>('.sf-root footer');
  31. if (footer) {
  32. return { element: footer, id: 'footer', type: 'footer' };
  33. }
  34. return null;
  35. }
  36. function clip(text: string | null | undefined, length = 80): string {
  37. const clean = (text ?? '').replace(/\s+/g, ' ').trim();
  38. return clean.length > length ? `${clean.slice(0, length - 1)}…` : clean;
  39. }
  40. /** Name one thing on the page in plain words, such as 'Button "Shop now"'. */
  41. function describe(element: HTMLElement): string {
  42. const tag = element.tagName.toLowerCase();
  43. if (tag === 'img') {
  44. const alt = clip((element as HTMLImageElement).alt, 60);
  45. return alt ? `Photo "${alt}"` : 'Photo';
  46. }
  47. if (tag === 'video' || tag === 'iframe') {
  48. return 'Video';
  49. }
  50. const text = clip(element.innerText || element.textContent);
  51. const kind = /^h[1-6]$/.test(tag)
  52. ? 'Heading'
  53. : tag === 'button' || element.getAttribute('role') === 'button'
  54. ? 'Button'
  55. : tag === 'a'
  56. ? 'Link'
  57. : 'Text';
  58. return text ? `${kind} "${text}"` : kind;
  59. }
  60. const THING =
  61. 'img, video, iframe, h1, h2, h3, h4, h5, h6, button, a, p, li, blockquote, summary, dt, dd';
  62. /** The meaningful thing under the pointer (a heading, photo, button…), inside its section. */
  63. function thingAt(target: Element, section: HTMLElement): HTMLElement | null {
  64. const thing = target.closest<HTMLElement>(THING);
  65. return thing && section.contains(thing) && thing !== section ? thing : null;
  66. }
  67. function overlap(a: DOMRect, b: DOMRect): number {
  68. const width = Math.min(a.right, b.right) - Math.max(a.left, b.left);
  69. const height = Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top);
  70. return width > 0 && height > 0 ? width * height : 0;
  71. }
  72. function box(
  73. doc: Document,
  74. style: Partial<CSSStyleDeclaration>,
  75. ): HTMLDivElement {
  76. const element = doc.createElement('div');
  77. Object.assign(
  78. element.style,
  79. {
  80. position: 'fixed',
  81. pointerEvents: 'none',
  82. zIndex: LAYER,
  83. display: 'none',
  84. } satisfies Partial<CSSStyleDeclaration>,
  85. style,
  86. );
  87. doc.body.appendChild(element);
  88. return element;
  89. }
  90. function place(
  91. element: HTMLElement,
  92. rect:
  93. | DOMRect
  94. | { left: number; top: number; width: number; height: number },
  95. ) {
  96. Object.assign(element.style, {
  97. display: 'block',
  98. left: `${rect.left}px`,
  99. top: `${rect.top}px`,
  100. width: `${rect.width}px`,
  101. height: `${rect.height}px`,
  102. });
  103. }
  104. /**
  105. * Turn on "Select to edit" inside the preview. The merchant can:
  106. * - click one thing (a heading, photo, button…) to pick it and its section, or
  107. * - drag a box over an area: the section it covers most is picked, with the things inside the box.
  108. * A green outline shows what would be picked. Escape stops. Returns a function that stops it.
  109. */
  110. export function startPicker(
  111. frame: HTMLIFrameElement,
  112. onPick: (selection: PreviewSelection) => void,
  113. onCancel: () => void,
  114. ): () => void {
  115. const doc = frame.contentDocument;
  116. const win = frame.contentWindow;
  117. if (!doc || !win || !doc.body) {
  118. return () => {};
  119. }
  120. // A clear layer over the page catches the pointer, so links and buttons do not react.
  121. const shield = box(doc, {
  122. inset: '0',
  123. pointerEvents: 'auto',
  124. cursor: 'crosshair',
  125. background: 'transparent',
  126. zIndex: '2147483645',
  127. });
  128. shield.style.display = 'block';
  129. const outline = box(doc, {
  130. border: `2px solid ${GREEN}`,
  131. borderRadius: '8px',
  132. background: 'rgba(16, 185, 129, 0.08)',
  133. });
  134. const area = box(doc, {
  135. border: `2px dashed ${GREEN}`,
  136. borderRadius: '6px',
  137. background: 'rgba(16, 185, 129, 0.12)',
  138. });
  139. const tag = doc.createElement('span');
  140. Object.assign(tag.style, {
  141. position: 'fixed',
  142. zIndex: '2147483647',
  143. pointerEvents: 'none',
  144. display: 'none',
  145. padding: '3px 9px',
  146. borderRadius: '999px',
  147. background: GREEN,
  148. color: '#fff',
  149. font: '600 12px/1.4 system-ui, sans-serif',
  150. whiteSpace: 'nowrap',
  151. maxWidth: '90vw',
  152. overflow: 'hidden',
  153. textOverflow: 'ellipsis',
  154. } satisfies Partial<CSSStyleDeclaration>);
  155. doc.body.appendChild(tag);
  156. /** The page element under a point, looking through our own layer. */
  157. const under = (x: number, y: number): Element | null =>
  158. doc
  159. .elementsFromPoint(x, y)
  160. .find(
  161. (element) =>
  162. element !== shield &&
  163. element !== outline &&
  164. element !== area &&
  165. element !== tag,
  166. ) ?? null;
  167. const label = (text: string, rect: DOMRect) => {
  168. tag.textContent = text;
  169. tag.style.display = 'block';
  170. tag.style.left = `${Math.max(rect.left, 4)}px`;
  171. tag.style.top = `${Math.max(rect.top - 26, 4)}px`;
  172. };
  173. /** What a click at this point would pick. */
  174. const atPoint = (x: number, y: number) => {
  175. const target = under(x, y);
  176. const section = sectionOf(target);
  177. if (!target || !section) {
  178. return null;
  179. }
  180. const thing = thingAt(target, section.element);
  181. return { section, thing };
  182. };
  183. /** What a box over this area would pick. */
  184. const inArea = (rect: DOMRect) => {
  185. let best: Found | null = null;
  186. let most = 0;
  187. doc.querySelectorAll<HTMLElement>(
  188. '[data-section], .sf-root header, .sf-root footer',
  189. ).forEach((element) => {
  190. const found = sectionOf(element);
  191. const covered = overlap(rect, element.getBoundingClientRect());
  192. if (found && found.element === element && covered > most) {
  193. best = found;
  194. most = covered;
  195. }
  196. });
  197. if (!best) {
  198. return null;
  199. }
  200. const chosen: Found = best;
  201. const things = [...chosen.element.querySelectorAll<HTMLElement>(THING)]
  202. // Things mostly inside the box (at least 60%), so a rough box still catches them.
  203. .filter((element) => {
  204. const inside = element.getBoundingClientRect();
  205. const size = inside.width * inside.height;
  206. return size > 0 && overlap(rect, inside) >= size * 0.6;
  207. })
  208. // Skip things inside another picked thing, such as a link inside a list item.
  209. .filter(
  210. (element, _, all) =>
  211. !all.some(
  212. (other) => other !== element && other.contains(element),
  213. ),
  214. );
  215. return { section: chosen, things };
  216. };
  217. let start: { x: number; y: number } | null = null;
  218. let dragging = false;
  219. const areaRect = (x: number, y: number) =>
  220. new DOMRect(
  221. Math.min(start!.x, x),
  222. Math.min(start!.y, y),
  223. Math.abs(x - start!.x),
  224. Math.abs(y - start!.y),
  225. );
  226. const onMove = (event: PointerEvent) => {
  227. if (
  228. start &&
  229. !dragging &&
  230. Math.hypot(event.clientX - start.x, event.clientY - start.y) >
  231. DRAG_START
  232. ) {
  233. dragging = true;
  234. }
  235. if (dragging) {
  236. const rect = areaRect(event.clientX, event.clientY);
  237. place(area, rect);
  238. const found = inArea(rect);
  239. if (found) {
  240. place(outline, found.section.element.getBoundingClientRect());
  241. label(
  242. `${sectionName(found.section.type)} · area`,
  243. found.section.element.getBoundingClientRect(),
  244. );
  245. }
  246. return;
  247. }
  248. const found = atPoint(event.clientX, event.clientY);
  249. if (!found) {
  250. outline.style.display = 'none';
  251. tag.style.display = 'none';
  252. return;
  253. }
  254. const shown = found.thing ?? found.section.element;
  255. const rect = shown.getBoundingClientRect();
  256. place(
  257. outline,
  258. new DOMRect(
  259. rect.left - 3,
  260. rect.top - 3,
  261. rect.width + 6,
  262. rect.height + 6,
  263. ),
  264. );
  265. label(
  266. found.thing
  267. ? `${sectionName(found.section.type)} › ${describe(found.thing).split(' "')[0]}`
  268. : sectionName(found.section.type),
  269. rect,
  270. );
  271. };
  272. const onDown = (event: PointerEvent) => {
  273. if (event.button !== 0) {
  274. return;
  275. }
  276. event.preventDefault();
  277. start = { x: event.clientX, y: event.clientY };
  278. dragging = false;
  279. // Keep getting the pointer even if it leaves the preview while drawing a box.
  280. try {
  281. shield.setPointerCapture(event.pointerId);
  282. } catch {
  283. // Not every pointer can be captured; drawing still works inside the preview.
  284. }
  285. };
  286. const onUp = (event: PointerEvent) => {
  287. if (!start) {
  288. return;
  289. }
  290. if (dragging) {
  291. const found = inArea(areaRect(event.clientX, event.clientY));
  292. start = null;
  293. dragging = false;
  294. area.style.display = 'none';
  295. if (found) {
  296. const detail = found.things
  297. .slice(0, 4)
  298. .map(describe)
  299. .join(', ');
  300. onPick({
  301. section: found.section.id,
  302. label: sectionName(found.section.type),
  303. detail: detail ? clip(`Area with: ${detail}`, 300) : null,
  304. });
  305. }
  306. return;
  307. }
  308. start = null;
  309. const found = atPoint(event.clientX, event.clientY);
  310. if (found) {
  311. onPick({
  312. section: found.section.id,
  313. label: sectionName(found.section.type),
  314. detail: found.thing ? describe(found.thing) : null,
  315. });
  316. }
  317. };
  318. const onKey = (event: KeyboardEvent) => {
  319. if (event.key === 'Escape') {
  320. onCancel();
  321. }
  322. };
  323. const onLeave = () => {
  324. if (!start) {
  325. outline.style.display = 'none';
  326. tag.style.display = 'none';
  327. }
  328. };
  329. shield.addEventListener('pointermove', onMove);
  330. shield.addEventListener('pointerdown', onDown);
  331. shield.addEventListener('pointerup', onUp);
  332. shield.addEventListener('pointerleave', onLeave);
  333. doc.addEventListener('keydown', onKey);
  334. return () => {
  335. doc.removeEventListener('keydown', onKey);
  336. shield.remove();
  337. outline.remove();
  338. area.remove();
  339. tag.remove();
  340. };
  341. }