import { useLocation } from "react-router-dom"; import { useSettings } from "@settings/contexts/SettingsContext"; export interface PlatformFrameUrlOptions { /** Hash path appended directly after /#/ (skips the site-scoped route/siteId/siteUrl construction). */ overridePath?: string; /** Site-scoped route - used when overridePath is not set. Builds /#/{route}/{siteId}/{siteUrl}. */ route?: string; /** Whether to include _wpnonce params (not needed for signup). callback_url is always included. Defaults to true. Defaults to true. */ includeAdminParams?: boolean; } const normalizeSiteUrl = (rawUrl: string): string => (rawUrl || "") .replace(/^https?:\/\//, "") .replace(/\/$/, "") .replace(/:\d+$/, "") .replace(/^localhost$/, "localhost.com"); /** * Builds the hash URL for an embedded platform.biogr.id iframe view. * * For site-scoped `route`s (overview/preferences), also carries forward the * same location.state-driven params (getAPI/startChat/api_verified) that the * old single Dashboard page used to append, so existing * navigate("/dashboard/overview", {state}) callers keep working (see WP-4406). * `action=goPremium` is now driven solely by `sfsyncData.is_premium` (see * WP-4505 — the Upgrade Plan popovers navigate to /upgrade-plan (see * WP-4564) directly instead of setting location.state.goPremium). */ export const usePlatformFrameUrl = ({ overridePath, route, includeAdminParams = true, }: PlatformFrameUrlOptions): string => { const { initialSettings } = useSettings(); const location = useLocation(); const { platformUrl } = process.env.CONFIG; const basePlatformUrl = (platformUrl || "").replace(/\/$/, ""); const siteId = initialSettings?.siteId || sfsyncData.siteId || ""; const siteUrl = normalizeSiteUrl(sfsyncData.siteUrl); const pluginVersion = encodeURIComponent(sfsyncRestAPI.pluginVersion || ""); const adminUrl = sfsyncData.dashboard_url || ""; const path = overridePath ?? `${route}/${siteId}/${siteUrl}`; let iframeURL = `${basePlatformUrl}/#/${path}?plugin_name=biogrid-wp&plugin_version=${pluginVersion}`; if (includeAdminParams) { iframeURL += `&_wpnonce=${encodeURIComponent(sfsyncRestAPI.nonceValue || "")}`; } iframeURL += `&site_url=${encodeURIComponent(siteUrl)}`; if (adminUrl) { iframeURL += `&callback_url=${encodeURIComponent(adminUrl)}`; } if (route) { const { is_premium: isPremium } = sfsyncData; const apiKeyVerified = initialSettings?.api_key_verified ?? false; const apiKey = initialSettings?.api_key ?? ""; if (isPremium) { iframeURL += "&action=goPremium"; } if (location?.state?.getAPI) { iframeURL += "&getAPI=true"; } if (apiKeyVerified) { iframeURL += `&api_verified=${apiKeyVerified}&api_key=${apiKey}`; } if (location?.state?.startChat) { iframeURL += "&startChat=Hello,%20I%20need%20support..."; } } return iframeURL; };