From aea04bca26e658a22cc3ca00b977638c2e6b22b1 Mon Sep 17 00:00:00 2001 From: hamed musallam Date: Thu, 18 Jul 2024 09:57:30 +0200 Subject: [PATCH] fix: print in firefox --- src/component/elements/print/PrintContent.tsx | 72 +++++++++++++++---- 1 file changed, 57 insertions(+), 15 deletions(-) diff --git a/src/component/elements/print/PrintContent.tsx b/src/component/elements/print/PrintContent.tsx index b5c58143e..7f02916eb 100644 --- a/src/component/elements/print/PrintContent.tsx +++ b/src/component/elements/print/PrintContent.tsx @@ -9,7 +9,14 @@ import { } from '@blueprintjs/core'; import { css } from '@emotion/react'; import { PageSizeName, PrintPageOptions } from 'nmr-load-save'; -import { CSSProperties, ReactNode, useEffect, useRef, useState } from 'react'; +import { + CSSProperties, + ReactNode, + useCallback, + useEffect, + useRef, + useState, +} from 'react'; import { createPortal } from 'react-dom'; import { Controller, useForm } from 'react-hook-form'; @@ -20,6 +27,8 @@ import { Select2Controller } from '../Select2Controller'; import { PrintProvider } from './PrintProvider'; +const isFirefox = navigator.userAgent.toLowerCase().includes("firefox"); + type Layout = 'portrait' | 'landscape'; interface BasePrintProps { @@ -34,7 +43,7 @@ interface InnerPrintFrameProps { } interface PrintFrameProps extends InnerPrintFrameProps, - Partial {} + Partial { } interface PageSize { name: PageSizeName; @@ -168,7 +177,6 @@ export function PrintContent(props: PrintFrameProps) { /> ); } - return ( pageItem.name === size)?.[layout] || {}; - useEffect(() => { + const handleAfterPrint = useCallback(() => { + onAfterPrint?.(); + }, [onAfterPrint]); + const handleBeforePrint = useCallback(() => { + onBeforePrint?.(); + }, [onBeforePrint]); + + + + const load = useCallback(() => { const contentWindow = frameRef.current?.contentWindow; if (!contentWindow) return; const document = contentWindow.document; @@ -214,28 +231,53 @@ export function InnerPrintFrame(props: InnerPrintFrameProps) { transferStyles(document); appendPrintPageStyle(document, { size, layout, margin }); - function handleAfterPrint() { - onAfterPrint?.(); - } - function handleBeforePrint() { - onBeforePrint?.(); - } - contentWindow.addEventListener('beforeprint', handleBeforePrint); contentWindow.addEventListener('afterprint', handleAfterPrint); + contentWindow.addEventListener('beforeprint', handleBeforePrint); + + return contentWindow; + }, [handleAfterPrint, handleBeforePrint, layout, margin, size]) + + useEffect(() => { + const contentWindow = frameRef.current?.contentWindow; + + if (!isFirefox) { + load(); + } return () => { + + if (!contentWindow) return; + contentWindow.removeEventListener('afterprint', handleAfterPrint); contentWindow.removeEventListener('beforeprint', handleBeforePrint); }; - }, [layout, onBeforePrint, onAfterPrint, margin, size]); + }, [onBeforePrint, onAfterPrint, handleBeforePrint, handleAfterPrint, size, layout, margin, load]); + + return ( - - + ); }