"use client"; /** * The live preview beside an editor: the page as it will look, with your saved drafts, on the right. * It folds away to a tab on the right edge (remembered in this browser), shows a desktop or a phone * width (the desktop scaled down to fit), and reloads where you were scrolled to each time * something is saved. On a small screen it's a button that opens it full screen. * * The frame's pages are the working copy because they're framed and you're signed in (site/load.ts). */ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; import { Eye, ExternalLink, Monitor, PanelRightClose, PanelRightOpen, RotateCw, Smartphone, X } from "lucide-react"; import { cx } from "./ui"; type Device = "desktop" | "phone"; const WIDTH: Record = { desktop: 1280, phone: 390 }; const OPEN_KEY = "ccw-admin-preview-open"; const DEVICE_KEY = "ccw-admin-preview-device"; const read = (k: string) => { try { return window.localStorage.getItem(k); } catch { return null; } }; const write = (k: string, v: string) => { try { window.localStorage.setItem(k, v); } catch { /* not kept */ } }; function Frame({ path, version, device }: { path: string; version: string; device: Device }) { const box = useRef(null); const frame = useRef(null); const scroll = useRef(0); const shown = useRef(version); const [size, setSize] = useState({ w: 0, h: 0 }); const [loading, setLoading] = useState(true); useLayoutEffect(() => { const el = box.current; if (!el) return; const ro = new ResizeObserver(([e]) => setSize({ w: e!.contentRect.width, h: e!.contentRect.height })); ro.observe(el); return () => ro.disconnect(); }, []); // A save: reload the page in the frame (wherever it was clicked to), back at the same place. useEffect(() => { if (shown.current === version) return; shown.current = version; const w = frame.current?.contentWindow; if (!w) return; try { scroll.current = w.scrollY; // eslint-disable-next-line react-hooks/set-state-in-effect setLoading(true); w.location.reload(); } catch { // Not the site's own page any more (a link out): leave it. } }, [version]); const onLoad = useCallback(() => { setLoading(false); const w = frame.current?.contentWindow; if (w && scroll.current) { try { w.scrollTo(0, scroll.current); } catch { /* elsewhere */ } scroll.current = 0; } }, []); // The page at its real width, scaled down to fit (a phone has a margin round it). const logical = WIDTH[device]; const pad = device === "phone" ? 12 : 0; const scale = size.w ? Math.min(1, (size.w - pad * 2) / logical) : 1; return (
{size.w > 0 && (