import electron , { BrowserWindow } from 'electron' ; import exportStory , { Storyboard } from './exportFrontend' ; import fs from 'fs' ; import path from 'path' ; import { previewDir } from './directories' ; import archiver from 'archiver' ; import { Server } from 'node-static' ; import fp from 'find-free-port' ; import http from 'http' ; electron . app . whenReady ( ) . then ( ( ) => { const fileServer = new Server ( previewDir , { cache : false } ) ; const PREVIEW_INDEX_PATH = path . join ( previewDir , 'index.html' ) ; let previewWindow = null ; electron . ipcMain . handle ( 'open-preview' , function preview ( event ) { if ( previewWindow ) { return previewWindow . focus ( ) ; } previewWindow = new BrowserWindow ( { width : 800 , height : 600 , autoHideMenuBar : true , } ) ; fp ( 4000 , 5000 , '127.0.0.1' , function ( err , freePort ) { http . createServer ( ( request , response ) => { request . addListener ( 'end' , function ( ) { fileServer . serve ( request , response ) ; } ) . resume ( ) ; } ) . listen ( freePort ) ; if ( previewWindow ) { previewWindow . loadURL ( `http://localhost:${ freePort }` ) ; } } ) ; previewWindow . on ( 'closed' , ( ) => { previewWindow = null ; } ) ; } ) ; electron . ipcMain . handle ( 'render-preview' , function preview ( event , storyboard ) { const indexHtmlContent = exportStory ( storyboard ) ; fs . writeFileSync ( PREVIEW_INDEX_PATH , indexHtmlContent ) ; if ( previewWindow ) { previewWindow . reload ( ) ; } } ) ; electron . ipcMain . handle ( 'export-as-zip' , async function ( event ) { const outputPath = electron . dialog . showSaveDialogSync ( { defaultPath : 'my-mural-website.zip' , properties : [ 'createDirectory' , 'showOverwriteConfirmation' ] , } ) ; if ( ! outputPath ) { return false ; } event . sender . send ( 'on-loading' , true ) ; const output = fs . createWriteStream ( outputPath ) ; const archive = archiver ( 'zip' , { zlib : { level : 9 } , } ) ; archive . on ( 'warning' , function ( err ) { if ( err . code === 'ENOENT' ) { } else { throw err ; } } ) ; archive . on ( 'error' , function ( err ) { throw err ; } ) ; archive . pipe ( output ) ; archive . directory ( previewDir , false ) ; await archive . finalize ( ) ; event . sender . send ( 'on-loading' , false ) ; } ) ; } ) ;