import { ILTRect } from 'polar-shared/src/util/rects/ILTRect' ; import { Canvases } from 'polar-shared/src/util/Canvases' ; import { ICapturedScreenshot } from './Screenshot' ; import { BrowserScreenshots } from './browser/BrowserScreenshots' ; import { FileType } from '../apps/main/file_loaders/FileType' ; import { Preconditions } from "polar-shared/src/Preconditions" ; /**
 * Captures screenshots of a document in the most elegant way possible.
 */ export namespace Screenshots { export interface CaptureOpts { readonly pageNum : number ; readonly boxRect : ILTRect ; readonly element ? : HTMLElement ; readonly fileType : FileType ; readonly docViewerElement : HTMLElement ; } /**
     * Capture a screenshot using the right strategy (via PDF canvas or
     * Electron)
     *
     */ export async function capture ( opts ) { const { pageNum , boxRect , element , fileType , docViewerElement } = opts ; Preconditions . assertPresent ( fileType , 'fileType' ) ; const captureDirectly = ( ) => { return captureViaBrowser ( boxRect , element ) ; } ; switch ( fileType ) { case 'pdf' : return captureViaCanvas ( pageNum , boxRect , docViewerElement ) ; case 'epub' : return captureDirectly ( ) ; } } async function captureViaCanvas ( pageNum , rect , docViewerElement ) { console . log ( "Capturing via canvas" ) ; function getPageElementForPage ( pageNum ) { const pages = docViewerElement . querySelectorAll ( ".page" ) ; return pages [ pageNum - 1 ] as HTMLElement ; } function getCanvasForPage ( pageNum ) { const pageElement = getPageElementForPage ( pageNum ) ; const canvas = pageElement . querySelector ( "canvas" ) as HTMLCanvasElement ; if ( ! canvas ) { throw new Error ( "Could not find canvas for page: " + pageNum ) ; } return canvas ; } const canvas = getCanvasForPage ( pageNum ) ; return await Canvases . extract ( canvas , rect ) ; } async function captureViaBrowser ( boxRect , element ? ) { const browserScreenshot = await BrowserScreenshots . capture ( boxRect , element ) ; if ( browserScreenshot ) { return { data : browserScreenshot . dataURL , type : browserScreenshot . type , width : boxRect . width , height : boxRect . height } ; } else { throw new Error ( "Unable to take screenshot via browser" ) ; } } export function computeCaptureRect ( rect , element ? ) { if ( element ) { const { width , height } = rect ; const boundingClientRect = element . getBoundingClientRect ( ) ; return { left : boundingClientRect . left , top : boundingClientRect . top , width , height } ; } return rect ; } }