| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252 |
- import { Crosshair } from 'lucide-react';
- import { createContext, useCallback, useContext, useMemo, useRef } from 'react';
- import type { ReactNode, RefObject } from 'react';
- import StoreDesignController from '@/actions/App/Http/Controllers/StoreDesignController';
- import { cn } from '@/lib/utils';
-
- /** What to point at in the preview: a section id ("header" and "footer" included) and its page. */
- export type PreviewTarget = {
- sectionId: string;
- /** The page the section is on. Header and footer are on every page, so null. */
- pageId: string | null;
- /** Shown on the outline, such as "Products". */
- label: string;
- };
-
- type Highlighter = {
- show: (target: PreviewTarget) => void;
- };
-
- const OVERLAY_ID = 'sf-design-highlight';
- const SHOW_FOR = 2600;
- /** How long a section waits for its page to open in the preview. */
- const WAIT_FOR_LOAD = 20000;
-
- function reducedMotion(): boolean {
- return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
- }
-
- /** The section's element in the preview page, or null when it is not on this page. */
- function findSection(doc: Document, sectionId: string): HTMLElement | null {
- if (sectionId === 'header') {
- return doc.querySelector<HTMLElement>('.sf-root header');
- }
-
- if (sectionId === 'footer') {
- return doc.querySelector<HTMLElement>('.sf-root footer');
- }
-
- return doc.querySelector<HTMLElement>(
- `[data-section="${CSS.escape(sectionId)}"]`,
- );
- }
-
- /**
- * Draw a green outline over the section inside the preview, scroll to it, and fade it out.
- * The outline follows the section on every frame, so it stays right while the page scrolls.
- */
- function outline(frame: HTMLIFrameElement, target: PreviewTarget): boolean {
- const doc = frame.contentDocument;
- const win = frame.contentWindow;
-
- if (!doc || !win || !doc.body) {
- return false;
- }
-
- const element = findSection(doc, target.sectionId);
-
- if (!element) {
- return false;
- }
-
- doc.getElementById(OVERLAY_ID)?.remove();
-
- const calm = reducedMotion();
- const box = doc.createElement('div');
- box.id = OVERLAY_ID;
- box.setAttribute('aria-hidden', 'true');
- Object.assign(box.style, {
- position: 'fixed',
- zIndex: '2147483647',
- pointerEvents: 'none',
- border: '3px solid #10b981',
- borderRadius: '10px',
- background: 'rgba(16, 185, 129, 0.08)',
- boxShadow: '0 0 0 4px rgba(16, 185, 129, 0.25)',
- transition: calm ? 'none' : 'opacity 300ms ease',
- opacity: '1',
- } satisfies Partial<CSSStyleDeclaration>);
-
- const tag = doc.createElement('span');
- tag.textContent = target.label;
- Object.assign(tag.style, {
- position: 'absolute',
- top: '8px',
- left: '8px',
- padding: '3px 9px',
- borderRadius: '999px',
- background: '#10b981',
- color: '#fff',
- font: '600 12px/1.4 system-ui, sans-serif',
- whiteSpace: 'nowrap',
- } satisfies Partial<CSSStyleDeclaration>);
- box.appendChild(tag);
- doc.body.appendChild(box);
-
- // The store's header stays at the top while scrolling, so other sections are shown below it.
- const isHeader = target.sectionId === 'header';
- const header = isHeader ? null : findSection(doc, 'header');
- const headerHeight = header?.offsetHeight ?? 0;
-
- // Tall sections line up under the header; short ones sit in the middle of the space left.
- const rect = element.getBoundingClientRect();
- const room = win.innerHeight - headerHeight;
- const pageTop = rect.top + win.scrollY;
- const top = isHeader
- ? 0
- : rect.height > room * 0.8
- ? pageTop - headerHeight - 8
- : pageTop - headerHeight - (room - rect.height) / 2;
- // Scroll only inside the preview; the Design page itself stays where it is.
- win.scrollTo({ top: Math.max(0, top), behavior: calm ? 'auto' : 'smooth' });
-
- const started = performance.now();
- const follow = () => {
- if (!box.isConnected) {
- return;
- }
-
- const now = element.getBoundingClientRect();
- const ceiling = header
- ? Math.max(header.getBoundingClientRect().bottom, 0)
- : 0;
- const shownTop = Math.max(now.top, ceiling);
- const shownBottom = Math.min(now.bottom, win.innerHeight);
- Object.assign(box.style, {
- top: `${shownTop + 2}px`,
- left: `${now.left + 2}px`,
- width: `${Math.max(now.width - 4, 0)}px`,
- height: `${Math.max(shownBottom - shownTop - 4, 0)}px`,
- });
-
- const age = performance.now() - started;
-
- if (age > SHOW_FOR) {
- box.style.opacity = '0';
- win.setTimeout(() => box.remove(), calm ? 0 : 320);
-
- return;
- }
-
- win.requestAnimationFrame(follow);
- };
- follow();
-
- return true;
- }
-
- /**
- * Points at sections in the Design tab's preview. Give the result to `PreviewHighlightContext`
- * so every box can use it, and pass `onLoad` to the preview iframe.
- */
- export function usePreviewHighlighter({
- frameRef,
- slug,
- homeUrl,
- }: {
- frameRef: RefObject<HTMLIFrameElement | null>;
- slug: string;
- homeUrl: string;
- }): Highlighter & { onLoad: () => void } {
- // A section on another page waits here while the preview opens that page.
- const waiting = useRef<{ target: PreviewTarget; at: number } | null>(null);
-
- const show = useCallback(
- (target: PreviewTarget) => {
- const frame = frameRef.current;
-
- if (!frame) {
- return;
- }
-
- // Bring the preview into view first, so the outline can be seen.
- frame.scrollIntoView({
- behavior: reducedMotion() ? 'auto' : 'smooth',
- block: 'nearest',
- });
-
- if (outline(frame, target)) {
- return;
- }
-
- const wanted =
- target.pageId && target.pageId !== 'home'
- ? StoreDesignController.page[
- '/stores/{slug}/preview/{pageId}'
- ].url({ slug, pageId: target.pageId })
- : homeUrl;
-
- if (frame.contentWindow?.location.pathname !== wanted) {
- waiting.current = { target, at: Date.now() };
- frame.src = wanted;
- }
- },
- [frameRef, slug, homeUrl],
- );
-
- const onLoad = useCallback(() => {
- const frame = frameRef.current;
- const pending = waiting.current;
- waiting.current = null;
-
- if (!frame || !pending || Date.now() - pending.at > WAIT_FOR_LOAD) {
- return;
- }
-
- // Give the store page a moment to draw before measuring.
- window.setTimeout(() => outline(frame, pending.target), 150);
- }, [frameRef]);
-
- return useMemo(() => ({ show, onLoad }), [show, onLoad]);
- }
-
- export const PreviewHighlightContext = createContext<Highlighter | null>(null);
-
- /**
- * A section's name that, when clicked, shows the section in the preview.
- * Without a preview around it, it is plain text.
- */
- export function SectionName({
- target,
- className,
- children,
- }: {
- target: PreviewTarget;
- className?: string;
- children: ReactNode;
- }) {
- const highlighter = useContext(PreviewHighlightContext);
-
- if (!highlighter) {
- return <span className={className}>{children}</span>;
- }
-
- return (
- <button
- type="button"
- onClick={() => highlighter.show(target)}
- title="Show in the preview"
- className={cn(
- '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',
- className,
- )}
- >
- <span className="min-w-0">{children}</span>
- <Crosshair
- className="size-3.5 shrink-0 translate-y-0.5 self-start text-muted-foreground opacity-60 group-hover/name:opacity-100"
- aria-hidden="true"
- />
- <span className="sr-only">(show in the preview)</span>
- </button>
- );
- }
|