import { URL } from "@cliqz/url-parser" ; import { Logger } from "src/shared/model/common" ; import { parsePackagedWebClientUrl } from "src/shared/util" ; import { resolveIpcMainApi } from "src/electron-preload/lib/util" ; import { resolveLink } from "src/electron-preload/lib/events-handling/lib" ; type ObservableElement = Pick < HTMLElement , "addEventListener" | "removeEventListener" > ; const processedClickElements = new WeakMap < ObservableElement , ReturnType < typeof registerDocumentClickEventListener > > ( ) ; export async function callDocumentClickEventListener < E extends Event = MouseEvent > ( event , logger , apiClient ? ) { const { element , link , href } = resolveLink ( event . target as Element ) ; if ( ! link || element . classList . contains ( "prevent-default-event" ) ) { return ; } if ( ! href ) { return ; } if ( parsePackagedWebClientUrl ( href ) ) { return ; } event . preventDefault ( ) ; if ( ! [ "https:" , "http:" ] . includes ( new URL ( href ) . protocol ) ) { return ; } const client = apiClient || resolveIpcMainApi ( { logger } ) ; const method = client ( "openExternal" ) ; await method ( { url : href } ) ; } export function registerDocumentClickEventListener < E extends ObservableElement > ( element , logger ) { let subscription = processedClickElements . get ( element ) ; if ( subscription ) { return subscription ; } const apiClient = resolveIpcMainApi ( { logger } ) ; const eventHandlerArgs = [ "click" , async ( event ) => callDocumentClickEventListener ( event , logger , apiClient ) , ] ; const [ , eventHandler ] = eventHandlerArgs ; element . addEventListener ( ... eventHandlerArgs ) ; subscription = { unsubscribe : ( ) => { element . removeEventListener ( ... eventHandlerArgs ) ; processedClickElements . delete ( element ) ; } , eventHandler , } ; processedClickElements . set ( element , subscription ) ; return subscription ; }