'use client'; import { ActionButton, ActionButtonGroup, Button, ButtonGroup, Content, createIcon, Dialog, DialogContainer, Heading, Link, Menu, MenuItem, MenuTrigger, Text, ToastQueue, Tooltip, TooltipTrigger } from '@react-spectrum/s2'; import {CopyButton} from './CopyButton'; import {createStackBlitz} from './StackBlitz'; import Download from '@react-spectrum/s2/icons/Download'; import type {DownloadFiles} from './CodeBlock'; import {getCodeSandboxFiles} from './CodeSandbox'; import {getParentElement} from 'react-aria/private/utils/shadowdom/DOMFunctions'; import {keyframes} from '../../../@react-spectrum/s2/style/style-macro' with {type: 'macro'}; import {Library} from './library'; import LinkIcon from '@react-spectrum/s2/icons/Link'; import OpenIn from '@react-spectrum/s2/icons/OpenIn'; // import Polygon4 from '@react-spectrum/s2/icons/Polygon4'; import Prompt from '@react-spectrum/s2/icons/Prompt'; import React, { createContext, ProviderProps, ReactNode, RefObject, useContext, useRef, useState } from 'react'; import {ShadcnCommand} from './ShadcnCommand'; import {style} from '@react-spectrum/s2/style' with {type: 'macro'}; import {zip} from './zip'; const platterStyle = style({ backgroundColor: 'layer-2', borderRadius: 'lg', '--code-padding-start': { type: 'paddingStart', value: 16 }, '--code-padding-end': { type: 'paddingEnd', value: 16 }, '--code-padding-y': { type: 'paddingTop', value: 16 }, position: 'relative' }); interface CodePlatterProps { children: ReactNode; type?: 'vanilla' | 'tailwind' | 's2'; showCoachMark?: boolean; } interface CodePlatterContextValue { library: Library; } const CodePlatterContext = createContext({library: 'react-spectrum'}); export function CodePlatterProvider(props: CodePlatterContextValue & {children: any}) { return {props.children}; } interface FileProviderContextValue extends DownloadFiles { entry?: string; } const FileProviderContext = createContext(null); export function FileProvider(props: ProviderProps) { return ; } const ShadcnContext = createContext<{ type: 'vanilla' | 'tailwind' | 'hooks'; component: string; } | null>(null); export function ShadcnProvider( props: ProviderProps<{type: 'vanilla' | 'tailwind' | 'hooks'; component: string} | null> ) { return ; } const ShareContext = createContext(null); export function ShareUrlProvider(props: ProviderProps) { return ; } export function CodePlatter({children, type, showCoachMark}: CodePlatterProps) { let codeRef = useRef(null); let [showShadcn, setShowShadcn] = useState(false); // let [showCodeSandbox, setShowCodeSandbox] = useState(false); let getText = () => getTextContent(codeRef.current!.querySelector('pre')!); let {library} = useContext(CodePlatterContext); if (!type) { if (library === 'react-aria') { // oxlint-disable-next-line react/react-compiler type = 'vanilla'; } else if (library === 'react-spectrum') { type = 's2'; } } let {files, deps = {}, urls = {}, entry} = useContext(FileProviderContext) ?? {}; let shadcn = useContext(ShadcnContext); let shareUrl = useContext(ShareContext); return (
{(shareUrl || files || shadcn) && ( Open in… {shareUrl && ( { // Find previous heading element to get hash. let url = new URL(shareUrl, location.href); let node: Element | null = codeRef.current; // Search for the nearest heading by walking up the tree and checking previous siblings while (node && node.tagName !== 'ARTICLE') { // Check previous siblings let sibling = node.previousElementSibling; while (sibling) { if (sibling instanceof HTMLHeadingElement) { node = sibling; break; } // Also check inside the sibling for headings let headingInSibling = sibling.querySelector('h1, h2, h3, h4, h5, h6'); if (headingInSibling instanceof HTMLHeadingElement) { node = headingInSibling; break; } sibling = sibling.previousElementSibling; } if (node instanceof HTMLHeadingElement) { break; } // Move up to parent node = getParentElement(node); } if (node instanceof HTMLHeadingElement && node.id) { url.hash = '#' + node.id; } navigator.clipboard.writeText(url.toString()).catch(() => { ToastQueue.negative('Failed to copy link.'); }); }}> Copy link )} {files && ( { let filesToDownload = getCodeSandboxFiles( getExampleFiles(codeRef, files, urls, entry), deps, type, entry ); let filesToZip = {}; for (let key in filesToDownload) { if ( filesToDownload[key] && !key.startsWith('.codesandbox') && !key.startsWith('.devcontainer') ) { filesToZip[key] = filesToDownload[key].content; } } let blob = zip(filesToZip); let a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'example.zip'; a.hidden = true; document.body.appendChild(a); a.click(); a.remove(); }}> Download ZIP )} {shadcn && ( setShowShadcn(true)}> Install with shadcn )} {/* {files && { setShowCodeSandbox(true); }}> Open in CodeSandbox } */} {files && ( { createStackBlitz( getExampleFiles(codeRef, files, urls, entry), deps, type, entry ); }}> Open in StackBlitz )} {/* registryUrl && Open in v0 */} )}
{children}
{/* setShowCodeSandbox(false)}> {showCodeSandbox && } */} setShowShadcn(false)}> {showShadcn && }
); } const pre = style({ borderRadius: 'lg', font: { default: 'code-xs', lg: 'code-sm' }, margin: 0, paddingStart: '--code-padding-start', paddingEnd: '--code-padding-end', paddingY: '--code-padding-y', width: 'fit', minWidth: 'full', boxSizing: 'border-box' }); export function Pre({children}) { return
{children}
; } function getExampleFiles( codeRef: RefObject, files: DownloadFiles['files'], urls: {[name: string]: string}, entry: string | undefined ): DownloadFiles['files'] { if (!entry) { return { ...files, 'Example.tsx': {contents: getExampleCode(codeRef, urls)} }; } return files; } function getTextContent(element: Element) { // Manually walk over text nodes inside the element and concatenate them. // This is like element.textContent except we skip anything inside an element with data-no-copy. let result = ''; let walker = document.createTreeWalker( element, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, node => { if (node.nodeType === Node.ELEMENT_NODE && (node as Element).hasAttribute('data-no-copy')) { result += '\n'; return NodeFilter.FILTER_REJECT; } return node.nodeType === Node.TEXT_NODE ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; } ); let node = walker.nextNode(); while (node) { result += node.nodeValue || ''; node = walker.nextNode(); } return result; } function getExampleCode(codeRef: RefObject, urls: {[name: string]: string}) { let code = getTextContent(codeRef.current!.querySelector('pre')!); let fileTabs = codeRef.current!.closest('[data-files]'); if (fileTabs) { let example = fileTabs.querySelector('[data-example] pre'); if (example) { code = getTextContent(example); } } if (!code.includes('export default function')) { // Export the last function code = code.replace( /\nfunction ([^(]+)((.|\n)+\n\}\n?)$/, '\nexport default function Example$2' ); } return ( code // Add function wrapper around raw JSX in examples. .replace(/\n<((?:.|\n)+)/, (_, code) => { let res = '\nexport default function Example() {\n return (\n <'; let lines = code.split('\n'); res += lines.shift(); for (let line of lines) { res += '\n ' + line; } res += '\n );\n}\n'; return res; }) // Resolve urls .replace(/import (.*?) from ['"](url:.*?)['"]/g, (_, name, specifier) => { return `const ${name} = '${urls[specifier]}'`; }) ); } // const V0 = createIcon(props => ( // // // // // )); const Flash = createIcon(props => ( )); function ShadcnDialog() { let {type, component} = useContext(ShadcnContext)!; let preRef = useRef(null); return ( {({close}) => ( <> Install with shadcn

Use the{' '} shadcn CLI {' '} to install {component} and its dependencies into your project.

)}
); } // function CodeSandboxDialog({getExampleFiles, codeRef, files, urls, entry, deps, type}) { // return ( // // {({close}) => (<> // Create a CodeSandbox // //

This will create an editable sandbox with this example in a new tab.

//

Troubleshooting: If the sandbox fails to open or isn't created, try logging in to CodeSandbox first. If you're already logged in, try signing out and back in.

//
// // // // // )} //
// ); // } const pulseAnimation = keyframes(` 0% { outline-width: 0px; transform: scale(100%); } 50% { outline-width: 8px; transform: scale(104%); } 100% { outline-width: 0px; transform: scale(100%); } `); const indicator = style({ animation: pulseAnimation, animationDuration: 2500, animationIterationCount: 'infinite', animationFillMode: 'forwards', animationTimingFunction: 'in-out', position: 'absolute', inset: 0, borderRadius: 'default', borderWidth: 2, borderColor: 'blue-800', borderStyle: 'solid', outlineColor: 'blue-800/20', outlineWidth: 4, outlineStyle: 'solid' }); const toolbar = style({ display: 'flex', justifyContent: 'end', padding: 4, position: 'absolute', top: 8, insetEnd: 8, backgroundColor: 'layer-2', boxShadow: 'elevated', borderRadius: 'default', zIndex: 1 }); function Toolbar({children, showCoachMark}) { if (showCoachMark) { children = ( <>
{children} ); } return
{children}
; }