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