UNPKG

16.3 kBJavaScriptView Raw
1import { queryFromString, parsePath, getMatch } from './chunk-AP4D5DJF.mjs';
2export { DEEPLY_EQUAL, buildArgsParam, deepDiff, getMatch, parsePath, queryFromLocation, queryFromString, stringifyQuery } from './chunk-AP4D5DJF.mjs';
3import React, { createContext, forwardRef, createElement, useCallback, useContext, useRef, useEffect, useMemo, useState, useLayoutEffect } from 'react';
4
5var scope=(()=>{let win;return typeof window<"u"?win=window:typeof globalThis<"u"?win=globalThis:typeof global<"u"?win=global:typeof self<"u"?win=self:win={},win})();function _extends(){return _extends=Object.assign?Object.assign.bind():function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key]);}return target},_extends.apply(this,arguments)}var Action;(function(Action2){Action2.Pop="POP",Action2.Push="PUSH",Action2.Replace="REPLACE";})(Action||(Action={}));var readOnly=function(obj){return Object.freeze(obj)};function warning(cond,message){if(!cond){typeof console<"u"&&console.warn(message);try{throw new Error(message)}catch{}}}var BeforeUnloadEventType="beforeunload";var PopStateEventType="popstate";function createBrowserHistory(options){options===void 0&&(options={});var _options=options,_options$window=_options.window,window2=_options$window===void 0?document.defaultView:_options$window,globalHistory=window2.history;function getIndexAndLocation(){var _window$location=window2.location,pathname=_window$location.pathname,search=_window$location.search,hash=_window$location.hash,state=globalHistory.state||{};return [state.idx,readOnly({pathname,search,hash,state:state.usr||null,key:state.key||"default"})]}var blockedPopTx=null;function handlePop(){if(blockedPopTx)blockers.call(blockedPopTx),blockedPopTx=null;else {var nextAction=Action.Pop,_getIndexAndLocation=getIndexAndLocation(),nextIndex=_getIndexAndLocation[0],nextLocation=_getIndexAndLocation[1];if(blockers.length)if(nextIndex!=null){var delta=index-nextIndex;delta&&(blockedPopTx={action:nextAction,location:nextLocation,retry:function(){go(delta*-1);}},go(delta));}else warning(!1,"You are trying to block a POP navigation to a location that was not created by the history library. The block will fail silently in production, but in general you should do all navigation with the history library (instead of using window.history.pushState directly) to avoid this situation.");else applyTx(nextAction);}}window2.addEventListener(PopStateEventType,handlePop);var action=Action.Pop,_getIndexAndLocation2=getIndexAndLocation(),index=_getIndexAndLocation2[0],location=_getIndexAndLocation2[1],listeners=createEvents(),blockers=createEvents();index==null&&(index=0,globalHistory.replaceState(_extends({},globalHistory.state,{idx:index}),""));function createHref(to){return typeof to=="string"?to:createPath(to)}function getNextLocation(to,state){return state===void 0&&(state=null),readOnly(_extends({pathname:location.pathname,hash:"",search:""},typeof to=="string"?parsePath2(to):to,{state,key:createKey()}))}function getHistoryStateAndUrl(nextLocation,index2){return [{usr:nextLocation.state,key:nextLocation.key,idx:index2},createHref(nextLocation)]}function allowTx(action2,location2,retry){return !blockers.length||(blockers.call({action:action2,location:location2,retry}),!1)}function applyTx(nextAction){action=nextAction;var _getIndexAndLocation3=getIndexAndLocation();index=_getIndexAndLocation3[0],location=_getIndexAndLocation3[1],listeners.call({action,location});}function push(to,state){var nextAction=Action.Push,nextLocation=getNextLocation(to,state);function retry(){push(to,state);}if(allowTx(nextAction,nextLocation,retry)){var _getHistoryStateAndUr=getHistoryStateAndUrl(nextLocation,index+1),historyState=_getHistoryStateAndUr[0],url=_getHistoryStateAndUr[1];try{globalHistory.pushState(historyState,"",url);}catch{window2.location.assign(url);}applyTx(nextAction);}}function replace(to,state){var nextAction=Action.Replace,nextLocation=getNextLocation(to,state);function retry(){replace(to,state);}if(allowTx(nextAction,nextLocation,retry)){var _getHistoryStateAndUr2=getHistoryStateAndUrl(nextLocation,index),historyState=_getHistoryStateAndUr2[0],url=_getHistoryStateAndUr2[1];globalHistory.replaceState(historyState,"",url),applyTx(nextAction);}}function go(delta){globalHistory.go(delta);}var history={get action(){return action},get location(){return location},createHref,push,replace,go,back:function(){go(-1);},forward:function(){go(1);},listen:function(listener){return listeners.push(listener)},block:function(blocker){var unblock=blockers.push(blocker);return blockers.length===1&&window2.addEventListener(BeforeUnloadEventType,promptBeforeUnload),function(){unblock(),blockers.length||window2.removeEventListener(BeforeUnloadEventType,promptBeforeUnload);}}};return history}function promptBeforeUnload(event){event.preventDefault(),event.returnValue="";}function createEvents(){var handlers=[];return {get length(){return handlers.length},push:function(fn){return handlers.push(fn),function(){handlers=handlers.filter(function(handler){return handler!==fn});}},call:function(arg){handlers.forEach(function(fn){return fn&&fn(arg)});}}}function createKey(){return Math.random().toString(36).substr(2,8)}function createPath(_ref){var _ref$pathname=_ref.pathname,pathname=_ref$pathname===void 0?"/":_ref$pathname,_ref$search=_ref.search,search=_ref$search===void 0?"":_ref$search,_ref$hash=_ref.hash,hash=_ref$hash===void 0?"":_ref$hash;return search&&search!=="?"&&(pathname+=search.charAt(0)==="?"?search:"?"+search),hash&&hash!=="#"&&(pathname+=hash.charAt(0)==="#"?hash:"#"+hash),pathname}function parsePath2(path){var parsedPath={};if(path){var hashIndex=path.indexOf("#");hashIndex>=0&&(parsedPath.hash=path.substr(hashIndex),path=path.substr(0,hashIndex));var searchIndex=path.indexOf("?");searchIndex>=0&&(parsedPath.search=path.substr(searchIndex),path=path.substr(0,searchIndex)),path&&(parsedPath.pathname=path);}return parsedPath}function invariant(cond,message){if(!cond)throw new Error(message)}function warning2(cond,message){if(!cond){typeof console<"u"&&console.warn(message);try{throw new Error(message)}catch{}}}var NavigationContext=createContext(null);NavigationContext.displayName="Navigation";var LocationContext=createContext(null);LocationContext.displayName="Location";var RouteContext=createContext({outlet:null,matches:[]});RouteContext.displayName="Route";function Router(_ref3){let{basename:basenameProp="/",children=null,location:locationProp,navigationType=Action.Pop,navigator,static:staticProp=!1}=_ref3;useInRouterContext()&&invariant(!1,"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let basename=normalizePathname(basenameProp),navigationContext=useMemo(()=>({basename,navigator,static:staticProp}),[basename,navigator,staticProp]);typeof locationProp=="string"&&(locationProp=parsePath2(locationProp));let{pathname="/",search="",hash="",state=null,key="default"}=locationProp,location=useMemo(()=>{let trailingPathname=stripBasename(pathname,basename);return trailingPathname==null?null:{pathname:trailingPathname,search,hash,state,key}},[basename,pathname,search,hash,state,key]);return warning2(location!=null,'<Router basename="'+basename+'"> is not able to match the URL '+('"'+pathname+search+hash+'" because it does not start with the ')+"basename, so the <Router> won't render anything."),location==null?null:createElement(NavigationContext.Provider,{value:navigationContext},createElement(LocationContext.Provider,{children,value:{location,navigationType}}))}function useHref(to){useInRouterContext()||invariant(!1,"useHref() may be used only in the context of a <Router> component.");let{basename,navigator}=useContext(NavigationContext),{hash,pathname,search}=useResolvedPath(to),joinedPathname=pathname;if(basename!=="/"){let toPathname=getToPathname(to),endsWithSlash=toPathname!=null&&toPathname.endsWith("/");joinedPathname=pathname==="/"?basename+(endsWithSlash?"/":""):joinPaths([basename,pathname]);}return navigator.createHref({pathname:joinedPathname,search,hash})}function useInRouterContext(){return useContext(LocationContext)!=null}function useLocation(){return useInRouterContext()||invariant(!1,"useLocation() may be used only in the context of a <Router> component."),useContext(LocationContext).location}function useNavigate(){useInRouterContext()||invariant(!1,"useNavigate() may be used only in the context of a <Router> component.");let{basename,navigator}=useContext(NavigationContext),{matches}=useContext(RouteContext),{pathname:locationPathname}=useLocation(),routePathnamesJson=JSON.stringify(matches.map(match=>match.pathnameBase)),activeRef=useRef(!1);return useEffect(()=>{activeRef.current=!0;}),useCallback(function(to,options){if(options===void 0&&(options={}),warning2(activeRef.current,"You should call navigate() in a React.useEffect(), not when your component is first rendered."),!activeRef.current)return;if(typeof to=="number"){navigator.go(to);return}let path=resolveTo(to,JSON.parse(routePathnamesJson),locationPathname);basename!=="/"&&(path.pathname=joinPaths([basename,path.pathname])),(options.replace?navigator.replace:navigator.push)(path,options.state);},[basename,navigator,routePathnamesJson,locationPathname])}function useResolvedPath(to){let{matches}=useContext(RouteContext),{pathname:locationPathname}=useLocation(),routePathnamesJson=JSON.stringify(matches.map(match=>match.pathnameBase));return useMemo(()=>resolveTo(to,JSON.parse(routePathnamesJson),locationPathname),[to,routePathnamesJson,locationPathname])}function resolvePath(to,fromPathname){fromPathname===void 0&&(fromPathname="/");let{pathname:toPathname,search="",hash=""}=typeof to=="string"?parsePath2(to):to;return {pathname:toPathname?toPathname.startsWith("/")?toPathname:resolvePathname(toPathname,fromPathname):fromPathname,search:normalizeSearch(search),hash:normalizeHash(hash)}}function resolvePathname(relativePath,fromPathname){let segments=fromPathname.replace(/\/+$/,"").split("/");return relativePath.split("/").forEach(segment=>{segment===".."?segments.length>1&&segments.pop():segment!=="."&&segments.push(segment);}),segments.length>1?segments.join("/"):"/"}function resolveTo(toArg,routePathnames,locationPathname){let to=typeof toArg=="string"?parsePath2(toArg):toArg,toPathname=toArg===""||to.pathname===""?"/":to.pathname,from;if(toPathname==null)from=locationPathname;else {let routePathnameIndex=routePathnames.length-1;if(toPathname.startsWith("..")){let toSegments=toPathname.split("/");for(;toSegments[0]==="..";)toSegments.shift(),routePathnameIndex-=1;to.pathname=toSegments.join("/");}from=routePathnameIndex>=0?routePathnames[routePathnameIndex]:"/";}let path=resolvePath(to,from);return toPathname&&toPathname!=="/"&&toPathname.endsWith("/")&&!path.pathname.endsWith("/")&&(path.pathname+="/"),path}function getToPathname(to){return to===""||to.pathname===""?"/":typeof to=="string"?parsePath2(to).pathname:to.pathname}function stripBasename(pathname,basename){if(basename==="/")return pathname;if(!pathname.toLowerCase().startsWith(basename.toLowerCase()))return null;let nextChar=pathname.charAt(basename.length);return nextChar&&nextChar!=="/"?null:pathname.slice(basename.length)||"/"}var joinPaths=paths=>paths.join("/").replace(/\/\/+/g,"/"),normalizePathname=pathname=>pathname.replace(/\/+$/,"").replace(/^\/*/,"/"),normalizeSearch=search=>!search||search==="?"?"":search.startsWith("?")?search:"?"+search,normalizeHash=hash=>!hash||hash==="#"?"":hash.startsWith("#")?hash:"#"+hash;function _extends2(){return _extends2=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key]);}return target},_extends2.apply(this,arguments)}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return {};var target={},sourceKeys=Object.keys(source),key,i;for(i=0;i<sourceKeys.length;i++)key=sourceKeys[i],!(excluded.indexOf(key)>=0)&&(target[key]=source[key]);return target}var _excluded=["onClick","reloadDocument","replace","state","target","to"],_excluded2=["aria-current","caseSensitive","className","end","style","to"];function BrowserRouter(_ref){let{basename,children,window:window2}=_ref,historyRef=useRef();historyRef.current==null&&(historyRef.current=createBrowserHistory({window:window2}));let history=historyRef.current,[state,setState]=useState({action:history.action,location:history.location});return useLayoutEffect(()=>history.listen(setState),[history]),createElement(Router,{basename,children,location:state.location,navigationType:state.action,navigator:history})}function isModifiedEvent(event){return !!(event.metaKey||event.altKey||event.ctrlKey||event.shiftKey)}var Link=forwardRef(function(_ref3,ref){let{onClick,reloadDocument,replace=!1,state,target,to}=_ref3,rest=_objectWithoutPropertiesLoose(_ref3,_excluded),href=useHref(to),internalOnClick=useLinkClickHandler(to,{replace,state,target});function handleClick(event){onClick&&onClick(event),!event.defaultPrevented&&!reloadDocument&&internalOnClick(event);}return createElement("a",_extends2({},rest,{href,onClick:handleClick,ref,target}))});Link.displayName="Link";var NavLink=forwardRef(function(_ref4,ref){let{"aria-current":ariaCurrentProp="page",caseSensitive=!1,className:classNameProp="",end=!1,style:styleProp,to}=_ref4,rest=_objectWithoutPropertiesLoose(_ref4,_excluded2),location=useLocation(),path=useResolvedPath(to),locationPathname=location.pathname,toPathname=path.pathname;caseSensitive||(locationPathname=locationPathname.toLowerCase(),toPathname=toPathname.toLowerCase());let isActive=locationPathname===toPathname||!end&&locationPathname.startsWith(toPathname)&&locationPathname.charAt(toPathname.length)==="/",ariaCurrent=isActive?ariaCurrentProp:void 0,className;typeof classNameProp=="function"?className=classNameProp({isActive}):className=[classNameProp,isActive?"active":null].filter(Boolean).join(" ");let style=typeof styleProp=="function"?styleProp({isActive}):styleProp;return createElement(Link,_extends2({},rest,{"aria-current":ariaCurrent,className,ref,style,to}))});NavLink.displayName="NavLink";function useLinkClickHandler(to,_temp){let{target,replace:replaceProp,state}=_temp===void 0?{}:_temp,navigate=useNavigate(),location=useLocation(),path=useResolvedPath(to);return useCallback(event=>{if(event.button===0&&(!target||target==="_self")&&!isModifiedEvent(event)){event.preventDefault();let replace=!!replaceProp||createPath(location)===createPath(path);navigate(to,{replace,state});}},[location,navigate,path,replaceProp,state,target,to])}var {document:document2}=scope,getBase=()=>`${document2.location.pathname}?`,useNavigate2=()=>{let navigate=useNavigate();return useCallback((to,{plain,...options}={})=>{if(typeof to=="string"&&to.startsWith("#")){document2.location.hash=to;return}if(typeof to=="string"){let target=plain?to:`?path=${to}`;return navigate(target,options)}if(typeof to=="number")return navigate(to)},[])},Link2=({to,children,...rest})=>React.createElement(Link,{to:`${getBase()}path=${to}`,...rest},children);Link2.displayName="QueryLink";var Location=({children})=>{let location=useLocation(),{path,singleStory}=queryFromString(location.search),{viewMode,storyId,refId}=parsePath(path);return React.createElement(React.Fragment,null,children({path:path||"/",location,viewMode,storyId,refId,singleStory:singleStory==="true"}))};Location.displayName="QueryLocation";function Match({children,path:targetPath,startsWith=!1}){return React.createElement(Location,null,({path:urlPath,...rest})=>children({match:getMatch(urlPath,targetPath,startsWith),...rest}))}Match.displayName="QueryMatch";function Route2(input){let{children,...rest}=input;return rest.startsWith===void 0&&(rest.startsWith=!1),React.createElement(Match,{...rest},({match})=>match?children:null)}Route2.displayName="Route";var LocationProvider=(...args)=>BrowserRouter(...args),BaseLocationProvider=(...args)=>Router(...args);
6
7export { BaseLocationProvider, Link2 as Link, Location, LocationProvider, Match, Route2 as Route, useNavigate2 as useNavigate };