Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

3.8 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { getLogger } from "@carbon/logger";
import { Spinner } from "@carbon/react";
import { useEffect, useRef, useState } from "react";
import { useDocumentTemplate, useEditorStore } from "./context";

const logger = getLogger("erp", "templatepreview");

const PREVIEW_DEBOUNCE_MS = 500;

/**
 * Server-rendered preview. The PDF is generated by the `.preview` route (Node,
 * where @react-pdf/renderer's Buffer/stream deps exist) and shown in the
 * browser's native PDF viewer via an iframe. No client-side react-pdf, no
 * polyfills, and the preview is byte-identical to the real document route.
 */
export function TemplatePreview({ previewPath }: { previewPath: string }) {
  const {
    blocks,
    theme,
    settings,
    headerSectionId,
    footerSectionId,
    headerConfig,
    previewId
  } = useDocumentTemplate();
  const previewNonce = useEditorStore((s) => s.previewNonce);
  const labelSizeId = useEditorStore((s) => s.labelSizeId);
  const [url, setUrl] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const urlRef = useRef<string | null>(null);

  // biome-ignore lint/correctness/useExhaustiveDependencies: `previewNonce` is a manual retrigger — bumped by the toolbar refresh button to re-run the fetch.
  useEffect(() => {
    const controller = new AbortController();
    const handle = setTimeout(async () => {
      setIsLoading(true);
      try {
        const formData = new FormData();
        formData.append("blocks", JSON.stringify(blocks));
        formData.append("theme", JSON.stringify(theme));
        formData.append("settings", JSON.stringify(settings));
        formData.append("headerSectionId", headerSectionId ?? "");
        formData.append("footerSectionId", footerSectionId ?? "");
        formData.append("headerConfig", JSON.stringify(headerConfig));
        formData.append("labelSizeId", labelSizeId);
        if (previewId) formData.append("previewId", previewId);
        const response = await fetch(previewPath, {
          method: "post",
          body: formData,
          signal: controller.signal
        });
        if (!response.ok) return;
        const blob = await response.blob();
        const nextUrl = URL.createObjectURL(blob);
        if (urlRef.current) URL.revokeObjectURL(urlRef.current);
        urlRef.current = nextUrl;
        setUrl(nextUrl);
      } catch (error) {
        if (!controller.signal.aborted) logger.error("Error", { error: error });
      } finally {
        if (!controller.signal.aborted) setIsLoading(false);
      }
    }, PREVIEW_DEBOUNCE_MS);

    return () => {
      controller.abort();
      clearTimeout(handle);
    };
    // `headerConfig` is a dep so logo/header edits (sent in the payload and
    // applied server-side) retrigger a fresh render without a save round-trip.
  }, [
    blocks,
    theme,
    settings,
    headerSectionId,
    footerSectionId,
    headerConfig,
    previewId,
    previewPath,
    previewNonce,
    labelSizeId
  ]);

  // Revoke the last object URL on unmount.
  useEffect(
    () => () => {
      if (urlRef.current) URL.revokeObjectURL(urlRef.current);
    },
    []
  );

  return (
    <div className="relative mx-auto flex h-full w-full max-w-3xl flex-col overflow-hidden rounded-lg border bg-card shadow-sm">
      {url && (
        <iframe
          key={url}
          src={url}
          title="Document preview"
          className="block h-full w-full grow border-none"
        />
      )}
      {isLoading && (
        <div className="absolute inset-0 flex items-center justify-center bg-background/60 backdrop-blur-[1px]">
          <Spinner className="size-6" />
        </div>
      )}
    </div>
  );
}