/** * WordPress dependencies */ import { addQueryArgs } from '@safe-wordpress/url'; export function addFreeTracker( link: string ): string { return addQueryArgs( link, { utm_source: 'nelio-ab-testing', utm_medium: 'plugin', utm_campaign: 'free', } ); } export function isExternalLink( link: string ): boolean { // Internal link. if ( ! /^[a-z]+:\/\//.test( link ) ) { return false; } link = link.replace( /^https?:\/\//, 'http://' ); const currentDomain = document.location.href .replace( /^https?:\/\//, '' ) .replace( /\/.*$/, '' ); if ( 0 === link.indexOf( 'http://' + currentDomain ) ) { return false; } return true; } export function disableExternalLinks(): void { Array.from( document.querySelectorAll( 'a' ) ).forEach( ( link ) => { const href = link.getAttribute( 'href' ) || ''; if ( ! isExternalLink( href ) ) { return; } link.classList.add( 'nab-disabled-link' ); link.addEventListener( 'click', ( ev ) => ev.preventDefault() ); } ); } export function addParamToLocalLinks( paramName: string, paramValue?: number | string | boolean ): void { Array.from( document.querySelectorAll( 'a' ) ).forEach( ( link ) => { const href = link.getAttribute( 'href' ) || ''; if ( isExternalLink( href ) ) { return; } // HACK. Remove fragment stuff when this pull request is finally merged: https://github.com/WordPress/gutenberg/pull/16656 const cleanUrl = href.replace( /#.*$/, '' ); const fragment = href.replace( /^[^#]*/, '' ); const finalUrl = addQueryArgs( cleanUrl, { [ paramName ]: paramValue ?? '' } ) + fragment; link.setAttribute( 'href', finalUrl ); } ); }