import { DialogFooter, Tag } from '@blueprintjs/core'; import { revalidateLogic } from '@tanstack/react-form'; import { useSelector } from '@tanstack/react-store'; import type { PrintPageOptions } from '@zakodium/nmrium-core'; import type { CSSProperties, ReactNode } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react'; import { createPortal } from 'react-dom'; import { AppForm, Button, coerceNumberInput, useForm } from 'react-science/ui'; import { z } from 'zod'; import { StandardDialog } from '../StandardDialog.tsx'; import { StyledDialogBody } from '../StyledDialogBody.js'; import { transferStylesToDocument } from '../utilities/transferStyles.ts'; import { PrintProvider } from './PrintProvider.js'; import { getSizesList, pageSizes } from './pageSize.js'; interface BasePrintProps { onPrint: (options: PrintPageOptions) => void; defaultPrintPageOptions: Partial; } interface InnerPrintFrameProps { children: ReactNode; onAfterPrint?: () => void; onBeforePrint?: () => void; onError?: (error: Error) => void; printPageOptions?: Partial; } interface PrintFrameProps extends InnerPrintFrameProps, Partial {} export function PrintContent(props: PrintFrameProps) { const [isPageOptionModalOpened, togglePageOptionDialog] = useState(false); const [pageOptions, setPageOptions] = useState | null>(); const { onBeforePrint, onAfterPrint, children, printPageOptions, defaultPrintPageOptions, onPrint, onError, } = props; useEffect(() => { function handleKeyDow(event: KeyboardEvent) { if ((event.ctrlKey || event.metaKey) && event.key === 'p') { event.preventDefault(); if (!printPageOptions) { togglePageOptionDialog(true); } else { setPageOptions(printPageOptions); } } } document.addEventListener('keydown', handleKeyDow); return () => { document.removeEventListener('keydown', handleKeyDow); }; }, [printPageOptions]); if (!pageOptions) { return ( { togglePageOptionDialog(false); }} onPrint={(options) => { togglePageOptionDialog(false); onPrint?.(options); setPageOptions(options); }} defaultPrintPageOptions={defaultPrintPageOptions || {}} /> ); } return ( <>
{ setPageOptions(null); onAfterPrint?.(); }} onBeforePrint={() => { onBeforePrint?.(); }} onError={(error) => { setPageOptions(null); onError?.(error); }} > {children} ); } function InnerPrintFrame(props: InnerPrintFrameProps) { const { children, onAfterPrint, onBeforePrint, onError, printPageOptions = {}, } = props; const { size = 'A4', margin = 0, layout = 'landscape', } = printPageOptions || {}; const [iframeDocument, setIframeDocument] = useState(); const { width = 0, height = 0 } = pageSizes.find((pageItem) => pageItem.name === size)?.[layout] || {}; const handleAfterPrint = useCallback(() => { onAfterPrint?.(); }, [onAfterPrint]); const handleBeforePrint = useCallback(() => { onBeforePrint?.(); }, [onBeforePrint]); function refHandler(frame: HTMLIFrameElement | null) { if (!frame) return; const targetDocument = frame.contentWindow?.document; if (!targetDocument) { onError?.(new Error('Print document is not available')); return; } transferStylesToDocument(targetDocument); appendPrintPageStyle(targetDocument, { size, layout, margin }); setIframeDocument(targetDocument); } useEffect(() => { const contentWindow = iframeDocument?.defaultView; if (!contentWindow) return; contentWindow.addEventListener('afterprint', handleAfterPrint); contentWindow.addEventListener('beforeprint', handleBeforePrint); return () => { contentWindow.removeEventListener('afterprint', handleAfterPrint); contentWindow.removeEventListener('beforeprint', handleBeforePrint); }; }, [iframeDocument, handleAfterPrint, handleBeforePrint]); return ( ); } function RenderContainer(props: { onRenderComplete: () => void; children: ReactNode; style?: CSSProperties; }) { const { onRenderComplete, style, children } = props; useEffect(() => { const handleRenderComplete = () => { // eslint-disable-next-line @eslint-react/web-api-no-leaked-timeout setTimeout(() => { onRenderComplete(); }, 250); }; const animationFrameId = requestAnimationFrame(handleRenderComplete); return () => { cancelAnimationFrame(animationFrameId); }; }, [onRenderComplete]); return
{children}
; } interface Style extends Pick { layout?: 'portrait' | 'landscape'; size?: string; } function appendPrintPageStyle(document: Document, style: Style = {}) { const { layout = 'landscape', size = 'A4' } = style; const styleElement = document.createElement('style'); styleElement.textContent = ` @media print { @page { size: ${size} ${layout}; padding:0; margin:0; } } `; document.head.append(styleElement); } interface InnerPrintOptionsModalProps extends BasePrintProps { onCloseDialog: () => void; } interface PrintOptionsModalProps extends InnerPrintOptionsModalProps { isOpen: boolean; } function PrintPageOptionsModal(props: PrintOptionsModalProps) { const { isOpen, ...otherProps } = props; if (!isOpen) return; return ; } const printOptionsValidation = z.object({ margin: coerceNumberInput(z.number().min(0)), layout: z.enum(['landscape', 'portrait']), size: z.enum([ 'Letter', 'Legal', 'Tabloid', 'Executive', 'Statement', 'Folio', 'A3', 'A4', 'A5', 'B4', 'B5', ]), }); type PrintPagOptionsInput = z.input; type PrintPagOptionsOutput = z.output; const INITIAL_VALUE: PrintPagOptionsInput = { size: 'A4', layout: 'landscape', margin: '0', }; function InnerPrintOptionsModal(props: InnerPrintOptionsModalProps) { const { onCloseDialog, onPrint, defaultPrintPageOptions } = props; const defaultValues = useMemo(() => { return { ...INITIAL_VALUE, ...defaultPrintPageOptions, }; }, [defaultPrintPageOptions]); const form = useForm({ defaultValues, validators: { onDynamic: printOptionsValidation, }, validationLogic: revalidateLogic({ mode: 'change' }), onSubmit: ({ value }) => { const parsedValues = printOptionsValidation.parse(value); onPrint(parsedValues); onCloseDialog?.(); }, }); const layoutStore = useSelector(form.store, (store) => store.values.layout); const sizesList = getSizesList(layoutStore); return ( {(field) => } {(field) => ( )} {(field) => ( cm} /> )} Print } /> ); }