Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
5.8 KB
Raw Blame
"use client";

/**
 * AttachmentPreviewPage — any attachment on a page of its own.
 *
 * Destination for "Open in new tab" in the attachment viewer, for every kind
 * the viewer shows. It renders the viewer's own top bar and stage
 * (`AttachmentPreviewStandalone`) so a file looks and behaves the same in both
 * places — the HTML viewport switch, a table's sorting, a log's line wrapping
 * — just with the whole tab to itself.
 *
 * The attachment record is loaded by id: the URL carries nothing else but the
 * display name (`?name=`), which titles the tab until the record lands.
 *
 * HTML keeps the viewer's security posture: iframe sandbox "allow-scripts"
 * only — no allow-same-origin, no allow-top-navigation — so the document runs
 * in an opaque origin and cannot reach cookies, localStorage, parent, or
 * top-level navigation. Here the iframe also reports its scroll position so a
 * desktop tab switch puts the reader back where they were.
 *
 * The route is workspace-scoped (`/{slug}/attachments/{id}/preview`) for
 * tenancy isolation; the attachment endpoints themselves are auth-checked, so
 * the slug is purely a URL contract.
 *
 * An HTML file opens at the `loc` the viewer handed over (its address bar,
 * MUL-7737). On desktop the address the reader left is kept in the tab's
 * view state, so a tab switch comes back to the same screen.
 */

import { useCallback, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { Loader2 } from "@multica/ui/icons";
import { api } from "@multica/core/api";
import { getPreviewKind } from "../editor/utils/preview";
import { useT } from "../i18n";
import { useRestoredViewState, useViewStateWriter } from "../platform";
import {
  AttachmentPreviewStandalone,
  type HtmlFrameRenderer,
} from "../editor/attachment-preview-modal";
import type { HtmlPreviewLocation } from "../editor/hooks/use-html-preview-location";
import { normalizeHtmlPreviewAddress } from "../editor/utils/iframe-location-bridge";
import { useHtmlPreviewScrollRestore } from "./use-html-preview-scroll-restore";

/** View-state key the page keeps an HTML file's address under. */
export const HTML_PREVIEW_ADDRESS_KEY = "html-preview-address";

interface AttachmentPreviewPageProps {
  attachmentId: string;
  /** Optional display name. Titles the tab until the record has loaded. */
  filename?: string;
  /** Query and fragment an HTML file opens at (the route's `loc`). */
  initialAddress?: string;
}

export function AttachmentPreviewPage({
  attachmentId,
  filename,
  initialAddress,
}: AttachmentPreviewPageProps) {
  const { t } = useT("editor");
  const query = useQuery({
    queryKey: ["attachment-preview-page", attachmentId] as const,
    queryFn: () => api.getAttachment(attachmentId),
    // Images authenticate once per page open; loaded streams stay stable.
    staleTime: Infinity,
    refetchOnMount: (query) =>
      query.state.data && getPreviewKind(
        query.state.data.content_type, query.state.data.filename,
      ) === "image" ? "always" : false,
    refetchOnWindowFocus: false,
    retry: false,
  });
  const attachment = query.data?.id === attachmentId ? query.data : null;
  const isImage = attachment &&
    getPreviewKind(attachment.content_type, attachment.filename) === "image";
  const imagePending = isImage && query.fetchStatus !== "idle";

  // Web shows this in the browser tab; on desktop it refines the window title
  // when the URL carries no `?name=` filename.
  const title = attachment?.filename || filename;
  useEffect(() => {
    if (title) document.title = title;
  }, [title]);

  const restoredAddress = useRestoredViewState(HTML_PREVIEW_ADDRESS_KEY);
  const writeViewState = useViewStateWriter();
  const keepAddress = useCallback(
    (address: string) => writeViewState(HTML_PREVIEW_ADDRESS_KEY, address),
    [writeViewState],
  );

  if (attachment && !(isImage && (imagePending || query.isError))) {
    return (
      <AttachmentPreviewStandalone
        attachment={attachment}
        currentImageMetadata={isImage ? attachment : undefined}
        renderHtmlFrame={renderPageHtmlFrame}
        initialHtmlAddress={normalizeHtmlPreviewAddress(
          restoredAddress ?? initialAddress ?? "",
        )}
        onHtmlAddressChange={keepAddress}
      />
    );
  }

  return (
    <div className="dark flex h-full w-full items-center justify-center gap-2 bg-black/95 px-4 text-body text-muted-foreground">
      {query.isPending || imagePending ? (
        <>
          <Loader2 className="size-4 animate-spin" />
          {t(($) => $.attachment.preview_loading)}
        </>
      ) : (
        <span data-testid="attachment-preview-page-error">
          {t(($) => $.attachment.preview_failed)}
        </span>
      )}
    </div>
  );
}

// Scroll-position restoration across desktop tab switches (multica-ai#6405).
// No-op on web (no desktop adapter). The iframe is keyed on contentKey so a
// content change (re-upload) structurally remounts a fresh document; the
// hook reports y=0 with the new key until that document scrolls, and
// messages from the previous document are dropped by token.
function PageHtmlFrame({
  html,
  title,
  location,
}: {
  html: string;
  title: string;
  location: HtmlPreviewLocation;
}) {
  const { contentKey, buildSrcDoc, iframeRef, onLoad } =
    useHtmlPreviewScrollRestore(html);
  const { frameRef } = location;
  const setFrame = useCallback(
    (el: HTMLIFrameElement | null) => {
      iframeRef(el);
      frameRef(el);
    },
    [iframeRef, frameRef],
  );
  return (
    <iframe
      key={`${contentKey}:${location.frameKey}`}
      ref={setFrame}
      onLoad={onLoad}
      srcDoc={location.withAddress(buildSrcDoc(html))}
      sandbox="allow-scripts"
      title={title}
      className="h-full w-full border-0 bg-background"
    />
  );
}

const renderPageHtmlFrame: HtmlFrameRenderer = (props) => (
  <PageHtmlFrame {...props} />
);