import { Subscription } from "rxjs" ; import { distinctUntilChanged , map } from "rxjs/operators" ; import { ElectronWindow } from "src/shared/model/electron" ; import { IPC_MAIN_API_NOTIFICATION_ACTIONS } from "src/shared/api/main-process/actions" ; import { ofType } from "src/shared/ngrx-util-of-type" ; const queryLinkElements = ( ( ) => { const shouldUseDarkColorsBasedFileEndings = { "true" : "-dark.css" , "false" : "-light.css" , } as const ; const result = ( shouldUseDarkColors , windowProxy ) => { return Array . from ( windowProxy . document . querySelectorAll < HTMLLinkElement > ( `head > link[href$="${ shouldUseDarkColorsBasedFileEndings [ shouldUseDarkColors ? "true" : "false" ] }"]` ) ) ; } ; return result ; } ) ( ) ; const applyTheming = ( shouldUseDarkColors , windowProxy ) : void => { for ( const linkElement of queryLinkElements ( shouldUseDarkColors , windowProxy ) ) { linkElement . rel = "stylesheet" ; } for ( const linkElement of queryLinkElements ( ! shouldUseDarkColors , windowProxy ) ) { const patch = { rel : "preload" , as : "style" } ; Object . assign ( linkElement , patch ) ; } } ; export const registerNativeThemeReaction = ( { buildIpcMainClient } , options ? ) : Subscription => { const subscription = new Subscription ( ) ; const windowProxy = options ?. windowProxy ?? window ; const shouldUseDarkColors = options ?. shouldUseDarkColors ; const finishPromise = new Promise < void > ( ( resolve ) => { const handlers = [ [ "beforeunload" , ( ) => resolve ] , [ "unload" , ( ) => resolve ] , ] as ReadonlyArray < Parameters < typeof window . addEventListener > > ; for ( const handler of handlers ) { window . addEventListener ( ... handler ) ; subscription . add ( { unsubscribe : ( ) => window . removeEventListener ( ... handler ) } ) ; } } ) ; subscription . add ( buildIpcMainClient ( { options : { finishPromise } } ) ( "notification" ) ( ) . pipe ( ofType ( IPC_MAIN_API_NOTIFICATION_ACTIONS . NativeTheme ) , map ( ( { payload : { shouldUseDarkColors } } ) => shouldUseDarkColors ) , distinctUntilChanged ( ) ) . subscribe ( ( shouldUseDarkColors ) => applyTheming ( shouldUseDarkColors , windowProxy ) ) ) ; if ( typeof shouldUseDarkColors === "boolean" ) { applyTheming ( shouldUseDarkColors , windowProxy ) ; } return subscription ; } ;