import a,{createContext as R,useEffect as v}from"react";import{useLocation as M,useNavigate as E}from"react-router-dom";import{useColorSwitcher as U}from"@redocly/theme/core/hooks";import{withPathPrefix as L}from"@redocly/theme/core/utils";import{ServerRoutes as x}from"../../../constants/index.js";import{normalizeRouteSlug as y,removeTrailingSlash as O}from"../../../shared/utils";import{loadAndNavigate as T}from"../../app/utils/loadAndNavigate";import{syncScrollWithEditor as z}from"../../app/utils/syncScrollWithEditor";import{PostMessageConnection as N}from"./PostMessageConnection";import{isHostnameOnDomain as c}from"../../app/utils/isHostnameOnDomain";const A=R({sendMessage:()=>{}});function F({children:i,enabled:o}){const C=E(),l=M(),n=a.useRef(null),{switchColorMode:m}=U(),u=a.useCallback(e=>{n.current?.send(e)},[]),h=a.useCallback(e=>{console.info("[PM] connection initialized."),n.current=new N(e.source,e.origin),u({type:"initialized"})},[u]),p=a.useCallback(async e=>{const{path:s="/",line:t=1,url:g}=e;let r=g;if(!g)try{const d=await fetch(L(x.RESOLVE_ROUTE_BY_PATH),{method:"POST",body:JSON.stringify(s+(t?`:${t}`:""))}),{route:k}=await d.json();r=k?.slug??k?.url??void 0}catch(d){console.error(d)}if(!r)return;r=r==="/"?"/":O(r);const[P,S]=r.split("#");y(P)===y(l.pathname)&&(S??"")===l.hash.substring(1)||(console.info("[PM] Update route to: ",r),await T({navigate:C,to:r,origin:"pm"}))},[l]),f=a.useCallback(async e=>{const{action:s}=e;switch(s){case"back":window.history.back();break;case"forward":window.history.forward();break;case"reload":window.location.reload();break}},[]),w=a.useCallback(e=>{window.scrollTo({top:e.position.absolute,behavior:"instant"})},[]),b=a.useCallback(e=>{m(e.colorSchema)},[m]);return v(()=>{if(!o)return;const e=async s=>{if(!_(s.origin))return;const t=s.data;switch(t.type){case"initialize":h(s);break;case"route-update":if(!n.current)return;p(t);break;case"location-update":if(!n.current)return;f(t);break;case"scroll-update":if(!n.current)return;w(t);break;case"editor-scroll-update":if(!n.current)return;z(t.percentScrolled,t.sequenceNumber);break;case"color-schema-update":if(!n.current)return;b(t);break}};return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}},[o,h,p,f,w,b]),a.createElement(A.Provider,{value:{sendMessage:u}},i)}function _(i){const o=new URL(i);return c(o.hostname,"localhost")||c(o.hostname,"127.0.0.1")||c(o.hostname,"blueharvest.cloud")||c(o.hostname,"bhstage.cloud")||c(o.hostname,"cloud.redocly.com")||c(o.hostname,"cloud.eu.redocly.com")||c(o.hostname,"cba.au.redocly.com")}export{A as PostMessageContext,F as PostMessageProvider};
