import * as React from 'react'; import { Page, useQueryParams, useRBAC, createContext, Form as FormContext, type FieldContentSourceMap, useNotification, } from '@strapi/admin/strapi-admin'; import { Box, Flex, FocusTrap, IconButton, Portal, SingleSelect, SingleSelectOption, } from '@strapi/design-system'; import { ArrowLineLeft } from '@strapi/icons'; import { useIntl } from 'react-intl'; import { useLocation, useParams } from 'react-router-dom'; import { styled, useTheme } from 'styled-components'; import { GetPreviewUrl } from '../../../../shared/contracts/preview'; import { COLLECTION_TYPES } from '../../constants/collections'; import { DocumentRBAC, useDocumentRBAC } from '../../features/DocumentRBAC'; import { type UseDocument, useDocument } from '../../hooks/useDocument'; import { type EditLayout, useDocumentLayout } from '../../hooks/useDocumentLayout'; import { Blocker } from '../../pages/EditView/components/Blocker'; import { FormLayout } from '../../pages/EditView/components/FormLayout'; import { handleInvisibleAttributes } from '../../pages/EditView/utils/data'; import { getPublishValidationErrors } from '../../pages/EditView/utils/forms'; import { buildValidParams } from '../../utils/api'; import { createYupSchema } from '../../utils/validation'; import { InputPopover } from '../components/InputPopover'; import { PreviewHeader } from '../components/PreviewHeader'; import { useGetPreviewUrlQuery } from '../services/preview'; import { INTERNAL_EVENTS, PUBLIC_EVENTS } from '../utils/constants'; import { getSendMessage } from '../utils/getSendMessage'; import type { Schema, UID } from '@strapi/types'; /* ------------------------------------------------------------------------------------------------- * Constants * -----------------------------------------------------------------------------------------------*/ const DEVICES = [ { name: 'desktop', label: { id: 'content-manager.preview.device.desktop', defaultMessage: 'Desktop', }, width: '100%', height: '100%', }, { name: 'mobile', label: { id: 'content-manager.preview.device.mobile', defaultMessage: 'Mobile', }, width: '375px', height: '667px', }, ]; /* ------------------------------------------------------------------------------------------------- * PreviewProvider * -----------------------------------------------------------------------------------------------*/ interface PopoverField extends FieldContentSourceMap { position: DOMRect; attribute: Schema.Attribute.AnyAttribute; blockIndex: number | null; } interface PreviewContextValue { url: string; title: string; document: NonNullable['document']>; meta: NonNullable['meta']>; schema: NonNullable['schema']>; components: NonNullable['components']>; layout: EditLayout; onPreview: () => void; iframeRef: React.RefObject; popoverField: PopoverField | null; setPopoverField: (value: PopoverField | null) => void; } type PreviewHighlightColors = { highlightHoverColor: string; highlightActiveColor: string; }; const [PreviewProvider, usePreviewContext] = createContext('PreviewPage'); const getPreviewScript = (() => { let previewScript = ''; return async (previewHighlightColors: PreviewHighlightColors) => { if (!previewScript) { const resp = await fetch(`${window.strapi.backendURL}/content-manager/preview/script`); if (!resp.ok) { throw new Error('Could not retrieve preview script from server.'); } previewScript = await resp.text(); if (!previewScript) { throw new Error('Could not retrieve preview script from server.'); } } return `(${previewScript})(${JSON.stringify({ colors: previewHighlightColors, events: INTERNAL_EVENTS, parentOrigin: window.location.origin, })})`; }; })(); /* ------------------------------------------------------------------------------------------------- * PreviewPage * -----------------------------------------------------------------------------------------------*/ const AnimatedArrow = styled(ArrowLineLeft)<{ $isSideEditorOpen: boolean }>` will-change: transform; rotate: ${(props) => (props.$isSideEditorOpen ? '0deg' : '180deg')}; transition: rotate 0.2s ease-in-out; `; const PreviewPage = () => { const location = useLocation(); const { formatMessage } = useIntl(); const theme = useTheme(); const iframeRef = React.useRef(null); const [isSideEditorOpen, setIsSideEditorOpen] = React.useState(true); const [popoverField, setPopoverField] = React.useState(null); const prevPopoverFieldRef = React.useRef(null); // When the popover closes, ask the iframe to rescan its stega element groups. // Live-preview sync updates the iframe DOM while editing, which can change the // rendered height of the field; groups need to reflect the current DOM so that // hover highlights and double-click detection work on the updated content. React.useEffect(() => { const prev = prevPopoverFieldRef.current; prevPopoverFieldRef.current = popoverField; if (prev !== null && popoverField === null) { const iframe = iframeRef.current; if (!iframe?.src) return; iframe.contentWindow?.postMessage( { type: INTERNAL_EVENTS.STRAPI_RESCAN_HIGHLIGHTS }, new URL(iframe.src).origin ); } }, [popoverField, iframeRef]); const { toggleNotification } = useNotification(); // Read all the necessary data from the URL to find the right preview URL const { slug: model, id: documentId, collectionType, } = useParams<{ slug: UID.ContentType; id: string; collectionType: string; }>(); const [{ query }] = useQueryParams<{ plugins?: { i18n?: { locale?: string } }; status?: string; }>(); const params = React.useMemo(() => buildValidParams(query), [query]); const [deviceName, setDeviceName] = React.useState<(typeof DEVICES)[number]['name']>( DEVICES[0].name ); const device = DEVICES.find((d) => d.name === deviceName) ?? DEVICES[0]; const previewHighlightColors: PreviewHighlightColors = { highlightHoverColor: theme.colors.primary500, highlightActiveColor: theme.colors.primary600, }; // Listen for ready message from iframe before injecting script React.useEffect(() => { const handleMessage = async (event: MessageEvent) => { // Only listen to events from the preview iframe if (iframeRef.current) { const previewOrigin = new URL(iframeRef.current?.src).origin; if (event.origin !== previewOrigin) { return; } } if (event.data?.type === PUBLIC_EVENTS.PREVIEW_READY) { try { const script = await getPreviewScript(previewHighlightColors); const sendMessage = getSendMessage(iframeRef); sendMessage(PUBLIC_EVENTS.STRAPI_SCRIPT, { script }); } catch { toggleNotification({ type: 'danger', message: formatMessage({ id: 'content-manager.preview.error.script-failed', defaultMessage: 'Could not load the live preview script. Visual editing may not be available.', }), }); } } }; window.addEventListener('message', handleMessage); return () => { window.removeEventListener('message', handleMessage); }; // Preserve the existing dependency behavior: previewHighlightColors is derived from theme. // eslint-disable-next-line react-hooks/exhaustive-deps }, [documentId, toggleNotification, theme, formatMessage]); if (!collectionType) { throw new Error('Could not find collectionType in url params'); } if (!model) { throw new Error('Could not find model in url params'); } // Only collection types must have a documentId if (collectionType === COLLECTION_TYPES && !documentId) { throw new Error('Could not find documentId in url params'); } const previewUrlResponse = useGetPreviewUrlQuery({ params: { contentType: model, }, query: { documentId, locale: params.locale as GetPreviewUrl.Request['query']['locale'], status: params.status as GetPreviewUrl.Request['query']['status'], }, }); const documentResponse = useDocument({ model, collectionType, documentId, params, }); const documentLayoutResponse = useDocumentLayout(model); const isLoadingActionsRBAC = useDocumentRBAC('PreviewPage', (state) => state.isLoading); const isLoading = previewUrlResponse.isLoading || documentLayoutResponse.isLoading || documentResponse.isLoading; if ( isLoadingActionsRBAC || (isLoading && (!documentResponse.document?.documentId || previewUrlResponse.isLoading)) ) { return ; } const initialValues = documentResponse.getInitialFormValues(); if ( previewUrlResponse.error || documentLayoutResponse.error || !documentResponse.document || !documentResponse.meta || !documentResponse.schema || !initialValues ) { return ; } if (!previewUrlResponse.data?.data?.url) { return ; } const documentTitle = documentResponse.getTitle(documentLayoutResponse.edit.settings.mainField); const previewUrl = previewUrlResponse.data.data.url; const onPreview = () => { iframeRef?.current?.contentWindow?.postMessage( { type: 'strapiUpdate' }, // The iframe origin is safe to use since it must be provided through the allowedOrigins config new URL(iframeRef.current.src).origin ); }; const hasAdvancedPreview = window.strapi.features.isEnabled('cms-advanced-preview'); return ( <> {formatMessage( { id: 'content-manager.preview.page-title', defaultMessage: '{contentType} preview', }, { contentType: documentTitle, } )} , options: Record) => { const { data: cleanedValues, removedAttributes } = handleInvisibleAttributes(values, { schema: documentResponse.schema, initialValues, components: documentResponse.components, }); const yupSchema = createYupSchema( documentResponse.schema?.attributes, documentResponse.components, { status: documentResponse.document?.status, removedAttributes, ...options, } ); return yupSchema.validate(cleanedValues, { abortEarly: false }); }} > {hasAdvancedPreview && ( )} {hasAdvancedPreview && ( setIsSideEditorOpen((prev) => !prev)} > )} setDeviceName(name.toString())} aria-label={formatMessage({ id: 'content-manager.preview.device.select', defaultMessage: 'Select device type', })} > {DEVICES.map((deviceOption) => ( {formatMessage(deviceOption.label)} ))} ); }; /* ------------------------------------------------------------------------------------------------- * ProtectedPreviewPage * -----------------------------------------------------------------------------------------------*/ const ProtectedPreviewPageImpl = () => { const { slug: model } = useParams<{ slug: string; }>(); const { permissions = [], isLoading, error, } = useRBAC([ { action: 'plugin::content-manager.explorer.read', subject: model }, { action: 'plugin::content-manager.explorer.update', subject: model }, { action: 'plugin::content-manager.explorer.publish', subject: model }, ]); if (isLoading) { return ; } if (error || !model) { return ( ); } return ( permission.action.includes('explorer.read') )} > ); }; const ProtectedPreviewPage = () => { return ( ); }; export { ProtectedPreviewPage, usePreviewContext }; export type { PreviewContextValue };