Last active
March 15, 2023 21:43
-
-
Save nkgentile/4bd92ce87980641e5a85865d9adfde55 to your computer and use it in GitHub Desktop.
Duplicate the current pane, switching to provided view ID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { type AllHTMLAttributes, forwardRef, useMemo } from 'react' | |
import { StateLink, type StateLinkProps } from 'sanity/router' | |
import { usePaneRouter } from 'sanity/desk' | |
export type SplitViewLinkProps = { | |
/** | |
* ID that references the view in the desk structure | |
* @see https://www.sanity.io/docs/structure-builder-reference#c0c8284844b7 | |
*/ | |
view: string | |
} & AllHTMLAttributes<HTMLAnchorElement>; | |
/** | |
* Curry provided `StateLink` component to push a new sibling view pane | |
* onto the router state. | |
*/ | |
export const SplitViewLink = forwardRef<HTMLAnchorElement, SplitViewLinkProps>(function GuideLink(props, ref) { | |
const { view, ...rest } = props | |
const { routerPanesState: currentPanes, groupIndex, siblingIndex } = usePaneRouter(); | |
/** | |
* Memoize next state from current panes | |
* and the active pane's position in the set | |
*/ | |
const nextState = useMemo<StateLinkProps['state']>(() => { | |
const currentGroup = currentPanes[groupIndex]; | |
const currentPane = currentGroup[siblingIndex]; | |
/** | |
* Duplicate current pane and pass view ID | |
* from document structure to sibling pane | |
*/ | |
const nextSibling = { | |
...currentPane, | |
params: { view }, | |
}; | |
const nextGroup = [ | |
...currentGroup.slice(0, siblingIndex + 1), | |
nextSibling, | |
...currentGroup.slice(siblingIndex + 1), | |
]; | |
const nextPanes = [ | |
...currentPanes.slice(0, groupIndex), | |
nextGroup, | |
...currentPanes.slice(groupIndex + 1), | |
]; | |
return { panes: nextPanes }; | |
}, [view, currentPanes, groupIndex, siblingIndex]); | |
return <StateLink ref={ref} {...rest} state={nextState} />; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
🔥