UNPKG

storybook-addon-remix-react-router

Version:

Use Remix React Router in your stories. (Formerly storybook-addon-react-router-v6)

15 lines (14 loc) 11.1 kB
import {makeDecorator,addons}from'@storybook/preview-api';import L,{useState,useMemo,useCallback,useRef}from'react';import {createMemoryRouter,RouterProvider,UNSAFE_RouteContext,useLocation,useParams,useSearchParams,useNavigationType}from'react-router';var y="storybook/react-router-v6",z="reactRouter",s={CLEAR:`${y}/clear`,NAVIGATION:`${y}/navigation`,STORY_LOADED:`${y}/story-loaded`,ROUTE_MATCHES:`${y}/route-matches`,ACTION_INVOKED:`${y}/action_invoked`,ACTION_SETTLED:`${y}/action_settled`,LOADER_INVOKED:`${y}/loader_invoked`,LOADER_SETTLED:`${y}/loader_settled`};var x=L.createContext([]);var S=L.createContext(void 0);function k(){let[e,t]=useState([]),n=UNSAFE_RouteContext;return n.Provider._context=new Proxy(n.Provider._context??{},{set(r,o,i){return o==="_currentValue"&&i!==void 0&&t(a=>i.matches.length>a.length?i.matches:a),Reflect.set(r,o,i)}}),e}function V(e){let t={};return e.forEach((n,r)=>{if(n instanceof File){t[r]={filename:n.name,filesize:n.size,filetype:n.type};return}t[r]=n;}),t}async function M(e){let t=e.clone(),n=t.headers.get("content-type")||"",r;switch(!0){case n.startsWith("text"):r=await t.text();break;case n.startsWith("application/json"):r=await t.json();break;case n.startsWith("multipart/form-data"):case n.startsWith("application/x-www-form-urlencoded"):{r=V(await t.formData());break}}return r}var E=()=>{let e=useRef(0);return useCallback(async(t,n)=>{e.current++;let r=`${t}_${e.current}`;switch(t){case s.ACTION_INVOKED:{let{request:o,params:i,context:a}=n,c={url:o.url,method:o.method,body:await M(o)};return {key:r,type:t,data:{params:i,request:c,context:a}}}case s.ACTION_SETTLED:return {key:r,type:t,data:n};case s.LOADER_INVOKED:{let{request:o,params:i,context:a}=n,c={url:o.url,method:o.method,body:await M(o)};return {key:r,type:t,data:{params:i,request:c,context:a}}}case s.LOADER_SETTLED:return {key:r,type:t,data:n}}},[])};function B(){let e=addons.getChannel(),t=E();return useCallback(n=>async function(r){if(n===void 0)return;e.emit(s.ACTION_INVOKED,await t(s.ACTION_INVOKED,r));let o=await n(r);return e.emit(s.ACTION_SETTLED,await t(s.ACTION_SETTLED,o)),o},[e,t])}function K(){let e=addons.getChannel(),t=E();return useCallback(n=>async function(r){if(n===void 0)return;e.emit(s.LOADER_INVOKED,await t(s.LOADER_INVOKED,r));let o=await n(r);return e.emit(s.LOADER_SETTLED,await t(s.LOADER_SETTLED,o)),o},[e,t])}function $(){let e=B(),t=K(),n=useCallback(r=>r.map(o=>{let{action:i,loader:a,children:c,lazy:d}=o,f={...o};return d&&(f.lazy=async function(){let l=await d(),h={...l};return typeof l.action=="function"&&(h.action=e(l.action)),typeof l.loader=="function"&&(h.loader=t(l.loader)),h}),typeof i=="function"&&(f.action=e(i)),typeof a=="function"&&(f.loader=t(a)),c&&(f.children=n(c)),f}),[e,t]);return n}var P=()=>{let e=L.useContext(S);if(e===void 0)throw new Error("useStory should be used inside <StoryContext>");return e};function C(e,t){return e.length===1&&(e[0].children===void 0||e[0].children.length===0)?[{...e[0],element:t}]:e.findIndex(r=>r.useStoryElement)!==-1?e.map(r=>r.useStoryElement?{...r,element:t}:r):e.map(r=>r.children?{...r,children:C(r.children,t)}:r)}var W;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE";})(W||(W={}));function xe(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Se(e,t){{typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}var Y;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error";})(Y||(Y={}));function N(e,t){t===void 0&&(t={});let n=e;n.endsWith("*")&&n!=="*"&&!n.endsWith("/*")&&(Se(!1,'Route path "'+n+'" will be treated as if it were '+('"'+n.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+n.replace(/\*$/,"/*")+'".')),n=n.replace(/\*$/,"/*"));let r=n.startsWith("/")?"/":"",o=a=>a==null?"":typeof a=="string"?a:String(a),i=n.split(/\/+/).map((a,c,d)=>{if(c===d.length-1&&a==="*")return o(t["*"]);let l=a.match(/^:([\w-]+)(\??)$/);if(l){let[,h,b]=l,p=t[h];return xe(b==="?"||p!=null,'Missing ":'+h+'" param'),o(p)}return a.replace(/\?$/g,"")}).filter(a=>!!a);return r+i.join("/")}var G=["post","put","patch","delete"];new Set(G);var Ee=["get",...G];new Set(Ee);function J({navigationHistory:e,location:t,routes:n}){if(e!==void 0){let p=[],D,w=Object.values(e);for(let g=0;g<w.length;g++){let{path:A,pathParams:U,searchParams:ie,hash:le,state:se,isInitialLocation:ue}=w[g];ue&&(D=g);let H=j(n),ce=(typeof A=="function"?A(H,U??{}):A)??H;p.push({pathname:N(ce??"/",U),search:new URLSearchParams(ie).toString(),hash:le,state:se});}return D??=p.length-1,{initialEntries:p,initialIndex:D}}let{path:r,pathParams:o,searchParams:i,hash:a,state:c}=t??{},d=j(n),l=(typeof r=="function"?r(d,o??{}):r)??d;return {initialEntries:[{pathname:N(l,o),search:new URLSearchParams(i).toString(),hash:a,state:c}],initialIndex:0}}function j(e=[],t="/"){if(e.length!==1)return t;let n=e[0],r=Pe(t,n.path);return n.children===void 0||n.children.length===0?r:j(n.children,r)}function Pe(e,t=""){let n=["","/"],r=e.split("/").filter(a=>!n.includes(a)),o=t.split("/").filter(a=>!n.includes(a));return "/"+[...r,...o].join("/")}function u(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function R(e,t){if(e===!1||e===null||typeof e>"u")throw console.warn("Test invariant failed:",t),new Error(t)}function T(e){return arguments.length===0?[]:Array.isArray(e)?e:[e]}function X(e){return e===void 0?[{path:"/"}]:typeof e=="string"?[{path:e}]:(e=T(e),e.length===1&&(e[0].path??="/"),e)}var O=()=>L.useContext(x);function Q(e){let t={};return e.forEach((n,r)=>{let o=t[r];if(typeof o=="string"){t[r]=[o,n];return}if(Array.isArray(o)){t[r]=[...o,n];return}t[r]=n;}),t}var Z=()=>{let e=useLocation(),t=e.pathname;return e.search.length>0&&(t+=`?${e.search}`),e.hash.length>0&&(t+=`#${e.hash}`),t};var q=()=>{let e=useRef(0),t=useLocation(),n=useParams(),[r]=useSearchParams(),o=useNavigationType(),i=O(),a=Q(r),c=Z(),d=i.map(l=>{let h={path:l.route.path};return Object.keys(l.params).length>0&&(h.params=l.params),h}),f={url:c,path:t.pathname,routeParams:n,searchParams:a,hash:t.hash,routeState:t.state,routeMatches:d};return l=>{e.current++;let h=`${l}_${e.current}`;switch(l){case s.STORY_LOADED:return {key:h,type:l,data:f};case s.NAVIGATION:return {key:h,type:l,data:{...f,navigationType:o}};case s.ROUTE_MATCHES:return {key:h,type:l,data:{matches:d}}}}};function _(){let{renderStory:e,storyContext:t}=P(),n=addons.getChannel(),r=useLocation(),o=O(),i=q(),a=useRef(),c=useRef(),d=useRef(),f=a.current!==void 0,l=f&&r.key!==a.current;return l&&c.current!==r.key&&(n.emit(s.NAVIGATION,i(s.NAVIGATION)),c.current=r.key),l&&o.length>0&&o!==d.current&&n.emit(s.ROUTE_MATCHES,i(s.ROUTE_MATCHES)),!f&&o.length>0&&(n.emit(s.STORY_LOADED,i(s.STORY_LOADED)),a.current=r.key,d.current=o),d.current=o,L.createElement(L.Fragment,null,e(t))}_.displayName="RouterLogger";function te(){let{addonParameters:e={}}=P(),{hydrationData:t,routing:n,navigationHistory:r,location:o,future:i,fallback:a}=e,c=$(),d=useMemo(()=>{let h=X(n),b=c(h),p=C(b,L.createElement(_,null)),{initialEntries:D,initialIndex:w}=J({navigationHistory:r,location:o,routes:p}),g={initialEntries:D,initialIndex:w,hydrationData:t};return i&&(g.future=i),createMemoryRouter(p,g)},[c,t,o,r,n,i]),f={},l=a??L.createElement(He,null);return i&&(f.future=i),i?.v7_partialHydration===!0&&(f.HydrateFallback=l),i?.v7_partialHydration===!1&&(f.fallbackElement=l),L.createElement(RouterProvider,{router:d,...f})}function He(){return L.createElement("p",null,"Performing initial data load")}var re=({renderStory:e,storyContext:t,addonParameters:n})=>{let r=k();return L.createElement(S.Provider,{value:{renderStory:e,storyContext:t,addonParameters:n}},L.createElement(x.Provider,{value:r},L.createElement(te,null)))};function oe(e){if(L.isValidElement(e))return !0;switch(!0){case L.isValidElement(e):case typeof e=="string":case typeof e=="number":case typeof e=="boolean":case e===null:case e===void 0:case(e instanceof Object&&u(e,Symbol.iterator)):return !0}return !1}function m(e){return oe(e)?{element:e}:e}function ae(e={}){let t=["location","navigationHistory","routing","future"];if(Object.keys(e??{}).some(o=>t.includes(o)))return e;let r={routing:{},location:{},hydrationData:void 0};if(u(e,"routePath")&&(r.location.path=e.routePath,r.routing.path=e.routePath),u(e,"routeParams")&&(r.location.pathParams=e.routeParams),u(e,"routeState")&&(r.location.state=e.routeState),u(e,"routeHandle")&&(r.routing.handle=e.routeHandle),u(e,"searchParams")&&(r.location.searchParams=e.searchParams),u(e,"browserPath")&&(r.location.path=e.browserPath),u(e,"loader")&&(r.routing.loader=e.loader),u(e,"action")&&(r.routing.action=e.action),u(e,"errorElement")&&(r.routing.errorElement=e.errorElement),u(e,"hydrationData")&&(r.hydrationData=e.hydrationData),u(e,"shouldRevalidate")&&(r.routing.shouldRevalidate=e.shouldRevalidate),u(e,"routeId")&&(r.routing.id=e.routeId),u(e,"outlet")){let o=m(e.outlet);o.path??="",r.routing.children=[o];}return r.routing.useStoryElement=!0,r}var Ve=makeDecorator({name:"withRouter",parameterName:z,wrapper:(e,t,{parameters:n})=>{let r=ae(n);return L.createElement(re,{renderStory:e,storyContext:t,addonParameters:r})}});function Be(e){return e}function v(e){let t={},n=[];return e.length===1&&(t={},n=e[0]),e.length===2&&(t=typeof e[0]=="string"?{path:e[0]}:m(e[0]),n=e[1]),[t,n]}function Ke(...e){let[t,n]=v(e);R(!u(t,"element"),"The story definition cannot contain the `element` property because the story element will be used");let r=m(n);return r.index=!0,[{...t,useStoryElement:!0,children:[r]}]}function $e(...e){let[t,n]=v(e);return R(!u(t,"element"),"The story definition cannot contain the `element` property because the story element will be used"),[{...t,useStoryElement:!0,children:n}]}function We(...e){let[t,n]=v(e);R(!u(t,"element"),"The story definition cannot contain the `element` property because the story element will be used");let r={},o=r;return n.forEach(i=>{let a=m(i);a.path??="",o.children=[a],o=a;},r),[{...t,useStoryElement:!0,children:[r]}]}function Ye(...e){let t=e.length===1?{}:e[0],n=T(e.length===1?e[0]:e[1]);R(!u(t,"element"),"The story definition cannot contain the `element` property because the story element will be used");let r={path:"/"},o=r;for(let i=0;i<n.length;i++){let a=n[i],c=m(a);c.path??="",o.children=[c],o=c;}return o.children=[{...t,index:!0,useStoryElement:!0}],[r]}/*! Bundled license information: @remix-run/router/dist/router.js: (** * @remix-run/router v1.21.0 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT *) */export{m as castRouterRoute,Ye as reactRouterNestedAncestors,We as reactRouterNestedOutlets,Ke as reactRouterOutlet,$e as reactRouterOutlets,Be as reactRouterParameters,Ve as withRouter};//# sourceMappingURL=index.js.map //# sourceMappingURL=index.js.map