All files / src/utils asset-path.ts

26.31% Statements 5/19
66.66% Branches 2/3
100% Functions 1/1
26.31% Lines 5/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31          1x 89x   89x                                       89x 89x  
/**
 * Utility for resolving public asset paths relative to the application's base URL.
 * Ensures robust asset loading on local dev servers, subfolder deployments,
 * and GitHub Pages (e.g. https://<user>.github.io/fll_sim/).
 */
export function resolveAssetUrl(relativePath: string): string {
  const clean = relativePath.replace(/^\.?\//, '');
 
  if (typeof window !== 'undefined' && window.location) {
    // Respect Vite's configured base URL (e.g., './' or '/fll_sim/')
    const base = import.meta.env?.BASE_URL || './';
 
    try {
      // If base is relative (like './'), resolve against the page's directory
      const pageDir = window.location.pathname.endsWith('/')
        ? window.location.pathname
        : window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1) || '/';
      
      const baseUrl = new URL(base, `${window.location.origin}${pageDir}`);
      return new URL(clean, baseUrl).href;
    } catch {
      const pageDir = window.location.pathname.endsWith('/')
        ? window.location.pathname
        : window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1) || '/';
      return `${window.location.origin}${pageDir}${clean}`;
    }
  }
 
  return `./${clean}`;
}