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-highlight.tsx 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import { Crosshair } from 'lucide-react';
  2. import { createContext, useCallback, useContext, useMemo, useRef } from 'react';
  3. import type { ReactNode, RefObject } from 'react';
  4. import StoreDesignController from '@/actions/App/Http/Controllers/StoreDesignController';
  5. import { cn } from '@/lib/utils';
  6. /** What to point at in the preview: a section id ("header" and "footer" included) and its page. */
  7. export type PreviewTarget = {
  8. sectionId: string;
  9. /** The page the section is on. Header and footer are on every page, so null. */
  10. pageId: string | null;
  11. /** Shown on the outline, such as "Products". */
  12. label: string;
  13. };
  14. type Highlighter = {
  15. show: (target: PreviewTarget) => void;
  16. };
  17. const OVERLAY_ID = 'sf-design-highlight';
  18. const SHOW_FOR = 2600;
  19. /** How long a section waits for its page to open in the preview. */
  20. const WAIT_FOR_LOAD = 20000;
  21. function reducedMotion(): boolean {
  22. return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  23. }
  24. /** The section's element in the preview page, or null when it is not on this page. */
  25. function findSection(doc: Document, sectionId: string): HTMLElement | null {
  26. if (sectionId === 'header') {
  27. return doc.querySelector<HTMLElement>('.sf-root header');
  28. }
  29. if (sectionId === 'footer') {
  30. return doc.querySelector<HTMLElement>('.sf-root footer');
  31. }
  32. return doc.querySelector<HTMLElement>(
  33. `[data-section="${CSS.escape(sectionId)}"]`,
  34. );
  35. }
  36. /**
  37. * Draw a green outline over the section inside the preview, scroll to it, and fade it out.
  38. * The outline follows the section on every frame, so it stays right while the page scrolls.
  39. */
  40. function outline(frame: HTMLIFrameElement, target: PreviewTarget): boolean {
  41. const doc = frame.contentDocument;
  42. const win = frame.contentWindow;
  43. if (!doc || !win || !doc.body) {
  44. return false;
  45. }
  46. const element = findSection(doc, target.sectionId);
  47. if (!element) {
  48. return false;
  49. }
  50. doc.getElementById(OVERLAY_ID)?.remove();
  51. const calm = reducedMotion();
  52. const box = doc.createElement('div');
  53. box.id = OVERLAY_ID;
  54. box.setAttribute('aria-hidden', 'true');
  55. Object.assign(box.style, {
  56. position: 'fixed',
  57. zIndex: '2147483647',
  58. pointerEvents: 'none',
  59. border: '3px solid #10b981',
  60. borderRadius: '10px',
  61. background: 'rgba(16, 185, 129, 0.08)',
  62. boxShadow: '0 0 0 4px rgba(16, 185, 129, 0.25)',
  63. transition: calm ? 'none' : 'opacity 300ms ease',
  64. opacity: '1',
  65. } satisfies Partial<CSSStyleDeclaration>);
  66. const tag = doc.createElement('span');
  67. tag.textContent = target.label;
  68. Object.assign(tag.style, {
  69. position: 'absolute',
  70. top: '8px',
  71. left: '8px',
  72. padding: '3px 9px',
  73. borderRadius: '999px',
  74. background: '#10b981',
  75. color: '#fff',
  76. font: '600 12px/1.4 system-ui, sans-serif',
  77. whiteSpace: 'nowrap',
  78. } satisfies Partial<CSSStyleDeclaration>);
  79. box.appendChild(tag);
  80. doc.body.appendChild(box);
  81. // The store's header stays at the top while scrolling, so other sections are shown below it.
  82. const isHeader = target.sectionId === 'header';
  83. const header = isHeader ? null : findSection(doc, 'header');
  84. const headerHeight = header?.offsetHeight ?? 0;
  85. // Tall sections line up under the header; short ones sit in the middle of the space left.
  86. const rect = element.getBoundingClientRect();
  87. const room = win.innerHeight - headerHeight;
  88. const pageTop = rect.top + win.scrollY;
  89. const top = isHeader
  90. ? 0
  91. : rect.height > room * 0.8
  92. ? pageTop - headerHeight - 8
  93. : pageTop - headerHeight - (room - rect.height) / 2;
  94. // Scroll only inside the preview; the Design page itself stays where it is.
  95. win.scrollTo({ top: Math.max(0, top), behavior: calm ? 'auto' : 'smooth' });
  96. const started = performance.now();
  97. const follow = () => {
  98. if (!box.isConnected) {
  99. return;
  100. }
  101. const now = element.getBoundingClientRect();
  102. const ceiling = header
  103. ? Math.max(header.getBoundingClientRect().bottom, 0)
  104. : 0;
  105. const shownTop = Math.max(now.top, ceiling);
  106. const shownBottom = Math.min(now.bottom, win.innerHeight);
  107. Object.assign(box.style, {
  108. top: `${shownTop + 2}px`,
  109. left: `${now.left + 2}px`,
  110. width: `${Math.max(now.width - 4, 0)}px`,
  111. height: `${Math.max(shownBottom - shownTop - 4, 0)}px`,
  112. });
  113. const age = performance.now() - started;
  114. if (age > SHOW_FOR) {
  115. box.style.opacity = '0';
  116. win.setTimeout(() => box.remove(), calm ? 0 : 320);
  117. return;
  118. }
  119. win.requestAnimationFrame(follow);
  120. };
  121. follow();
  122. return true;
  123. }
  124. /**
  125. * Points at sections in the Design tab's preview. Give the result to `PreviewHighlightContext`
  126. * so every box can use it, and pass `onLoad` to the preview iframe.
  127. */
  128. export function usePreviewHighlighter({
  129. frameRef,
  130. slug,
  131. homeUrl,
  132. }: {
  133. frameRef: RefObject<HTMLIFrameElement | null>;
  134. slug: string;
  135. homeUrl: string;
  136. }): Highlighter & { onLoad: () => void } {
  137. // A section on another page waits here while the preview opens that page.
  138. const waiting = useRef<{ target: PreviewTarget; at: number } | null>(null);
  139. const show = useCallback(
  140. (target: PreviewTarget) => {
  141. const frame = frameRef.current;
  142. if (!frame) {
  143. return;
  144. }
  145. // Bring the preview into view first, so the outline can be seen.
  146. frame.scrollIntoView({
  147. behavior: reducedMotion() ? 'auto' : 'smooth',
  148. block: 'nearest',
  149. });
  150. if (outline(frame, target)) {
  151. return;
  152. }
  153. const wanted =
  154. target.pageId && target.pageId !== 'home'
  155. ? StoreDesignController.page[
  156. '/stores/{slug}/preview/{pageId}'
  157. ].url({ slug, pageId: target.pageId })
  158. : homeUrl;
  159. if (frame.contentWindow?.location.pathname !== wanted) {
  160. waiting.current = { target, at: Date.now() };
  161. frame.src = wanted;
  162. }
  163. },
  164. [frameRef, slug, homeUrl],
  165. );
  166. const onLoad = useCallback(() => {
  167. const frame = frameRef.current;
  168. const pending = waiting.current;
  169. waiting.current = null;
  170. if (!frame || !pending || Date.now() - pending.at > WAIT_FOR_LOAD) {
  171. return;
  172. }
  173. // Give the store page a moment to draw before measuring.
  174. window.setTimeout(() => outline(frame, pending.target), 150);
  175. }, [frameRef]);
  176. return useMemo(() => ({ show, onLoad }), [show, onLoad]);
  177. }
  178. export const PreviewHighlightContext = createContext<Highlighter | null>(null);
  179. /**
  180. * A section's name that, when clicked, shows the section in the preview.
  181. * Without a preview around it, it is plain text.
  182. */
  183. export function SectionName({
  184. target,
  185. className,
  186. children,
  187. }: {
  188. target: PreviewTarget;
  189. className?: string;
  190. children: ReactNode;
  191. }) {
  192. const highlighter = useContext(PreviewHighlightContext);
  193. if (!highlighter) {
  194. return <span className={className}>{children}</span>;
  195. }
  196. return (
  197. <button
  198. type="button"
  199. onClick={() => highlighter.show(target)}
  200. title="Show in the preview"
  201. className={cn(
  202. 'group/name inline-flex max-w-full min-w-0 items-baseline gap-1.5 rounded-sm text-left underline-offset-4 hover:underline focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none',
  203. className,
  204. )}
  205. >
  206. <span className="min-w-0">{children}</span>
  207. <Crosshair
  208. className="size-3.5 shrink-0 translate-y-0.5 self-start text-muted-foreground opacity-60 group-hover/name:opacity-100"
  209. aria-hidden="true"
  210. />
  211. <span className="sr-only">(show in the preview)</span>
  212. </button>
  213. );
  214. }