repo_id
stringclasses
563 values
file_path
stringlengths
40
166
content
stringlengths
1
2.94M
__index_level_0__
int64
0
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Tooltip/index.ts
export { default } from "./Tooltip"; export type { TooltipProps } from "./Tooltip";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Tutorial/TutorialDetails.tsx
import { FC } from "react"; import styled, { css } from "styled-components"; import Link from "../Link"; import Tag from "../Tag"; import { Arrayable, TutorialDetailKey } from "../../utils/pg"; import { useDifferentBackground } from "../../hooks"; interface TutorialDetailsProps { details: ClickableTutorialDetailProps[]; } const TutorialDetails: FC<TutorialDetailsProps> = ({ details }) => { const { ref } = useDifferentBackground(); return ( <TutorialDetailsWrapper ref={ref}> {details.map(({ kind, data }) => { return ( data && ( <TutorialDetailSection key={kind}> <TutorialDetailName>{kind}</TutorialDetailName> <TutorialDetailWrapper> {Array.isArray(data) ? ( data.map((data) => ( <ClickableTutorialDetail key={data} kind={kind} data={data} /> )) ) : ( <ClickableTutorialDetail kind={kind} data={data} /> )} </TutorialDetailWrapper> </TutorialDetailSection> ) ); })} </TutorialDetailsWrapper> ); }; const TutorialDetailsWrapper = styled.div` ${({ theme }) => css` padding: 1rem; display: flex; flex-wrap: wrap; justify-content: space-between; column-gap: 2rem; row-gap: 1rem; border-radius: ${theme.default.borderRadius}; `} `; const TutorialDetailSection = styled.div` display: flex; flex-direction: column; gap: 0.5rem; `; const TutorialDetailName = styled.span` ${({ theme }) => css` font-weight: bold; text-transform: uppercase; letter-spacing: 0.3px; font-size: ${theme.font.other.size.small}; `} `; const TutorialDetailWrapper = styled.div` display: flex; flex-wrap: wrap; gap: 1rem; `; interface ClickableTutorialDetailProps { kind: TutorialDetailKey; data: Arrayable<string> | undefined; } const ClickableTutorialDetail: FC<ClickableTutorialDetailProps> = ({ data, ...props }) => ( <Link href={`/tutorials?${props.kind}=${data}`}> <Tag {...props} value={data} /> </Link> ); export default TutorialDetails;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Tutorial/Tutorial.tsx
import { FC, useEffect } from "react"; import styled, { css } from "styled-components"; import { About, Main } from "./views"; import { PgTheme, PgTutorial } from "../../utils/pg"; import { useRenderOnChange } from "../../hooks"; import type { TutorialComponentProps } from "./types"; export const Tutorial: FC<TutorialComponentProps> = ({ about, pages, files, defaultOpenFile, layout, onMount, onComplete, }) => { useRenderOnChange(PgTutorial.onDidChange); // On component mount useEffect(() => { if (onMount) return onMount(); }, [onMount]); return ( <Wrapper> {PgTutorial.view === "about" ? ( <About about={about} files={files} pages={pages} defaultOpenFile={defaultOpenFile} /> ) : ( <Main pages={pages} layout={layout} onComplete={onComplete} /> )} </Wrapper> ); }; const Wrapper = styled.div` ${({ theme }) => css` ${PgTheme.getScrollbarCSS({ allChildren: true })}; ${PgTheme.convertToCSS(theme.components.main.primary.tutorial.default)}; `} `;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Tutorial/types.ts
import type { TupleFiles } from "../../utils/pg"; export type TutorialComponentProps = { /** About section that will be shown under the description of the tutorial page */ about: TutorialElement; /* Tutorial pages to show next to the editor */ pages: Page[]; /** Initial files to have at the beginning of the tutorial */ files: TupleFiles; /** Initial open file when the tutorial/page is first loaded */ defaultOpenFile?: string; /** Callback to run when the tutorial is completed */ onComplete?: () => any; } & Pick<Page, "layout" | "onMount">; export type TutorialAboutComponentProps = Pick< TutorialComponentProps, "about" | "files" | "defaultOpenFile" | "pages" >; export type TutorialMainComponentProps = Pick< TutorialComponentProps, "pages" | "layout" | "onComplete" >; type Page = { /** Content of the page, can be either: * - Text string(Markdown supported) * - React component */ content: TutorialElement; /** Title of the page that will be used for navigation. * * Defaults to `pageNumber/pageCount`, e.g. 3/5 */ title?: string; /** * Layout of the tutorial component. * * @default "editor-content" */ layout?: "editor-content" | "content-only"; /** Callback to run on mount */ onMount?: () => any; }; /** Markdown string or JSX Element */ type TutorialElement = string | JSX.Element;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Tutorial/index.ts
export * from "./Tutorial"; export * from "./types";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Tutorial
solana_public_repos/solana-playground/solana-playground/client/src/components/Tutorial/views/Main.tsx
import { FC, useEffect, useRef } from "react"; import styled, { css } from "styled-components"; import Split from "react-split"; import Button from "../../Button"; import Markdown from "../../Markdown"; // TODO: Fix importing views from components import { EditorWithTabs } from "../../../views/main/primary/EditorWithTabs"; import { PointedArrow } from "../../Icons"; import { PgTheme, PgTutorial } from "../../../utils/pg"; import type { TutorialMainComponentProps } from "../types"; export const Main: FC<TutorialMainComponentProps> = ({ pages, layout = "editor-content", onComplete, }) => { const pageNumber = PgTutorial.pageNumber; const tutorialPageRef = useRef<HTMLDivElement>(null); // Scroll to the top on page change useEffect(() => { tutorialPageRef.current?.scrollTo({ top: 0, left: 0 }); }, [pageNumber]); // Specific page events useEffect(() => { if (!pageNumber) return; const page = pages[pageNumber - 1]; if (page.onMount) return page.onMount(); }, [pageNumber, pages]); const nextPage = () => { PgTutorial.pageNumber! += 1; }; const previousPage = () => { PgTutorial.pageNumber! -= 1; }; const finishTutorial = () => { PgTutorial.finish(); if (onComplete) onComplete(); }; if (!pageNumber) return null; const currentPage = pages.at(pageNumber - 1); if (!currentPage) { // This could happen if the saved page has been deleted PgTutorial.pageNumber = 1; return null; } const currentContent = currentPage.content; const currentLayout = currentPage.layout ?? layout; // TODO: Add a custom `Split` component because `react-split` doesn't properly // handle size and `children.length` changes const [Wrapper, props] = ( currentLayout === "content-only" ? [RegularWrapper, {}] : [SplitWrapper, { sizes: [60, 40] }] ) as [typeof RegularWrapper, {}]; return ( <Wrapper {...props}> {currentLayout === "editor-content" && <EditorWithTabs />} <TutorialPage ref={tutorialPageRef}> <TutorialContent> {typeof currentContent === "string" ? ( <Markdown>{currentContent}</Markdown> ) : ( currentContent )} <NavigationButtonsOutsideWrapper> <NavigationButtonsInsideWrapper> {pageNumber !== 1 && ( <PreviousWrapper> <PreviousText>Previous</PreviousText> <NavigationButton onClick={previousPage} kind="no-border" leftIcon={<PointedArrow rotate="180deg" />} > {pages[pageNumber - 2].title ?? `${pageNumber - 1}/${pages.length}`} </NavigationButton> </PreviousWrapper> )} <NextWrapper> <NextText>Next</NextText> {pageNumber === pages.length ? ( <NavigationButton onClick={finishTutorial} kind="no-border" color="success" rightIcon={<span>✔</span>} > Finish </NavigationButton> ) : ( <NavigationButton onClick={nextPage} kind="no-border" rightIcon={<PointedArrow />} > {pages[pageNumber].title ?? `${pageNumber + 1}/${pages.length}`} </NavigationButton> )} </NextWrapper> </NavigationButtonsInsideWrapper> </NavigationButtonsOutsideWrapper> </TutorialContent> </TutorialPage> </Wrapper> ); }; const RegularWrapper = styled.div``; const SplitWrapper = styled(Split)` display: flex; width: 100%; height: -webkit-fill-available; max-height: 100%; overflow: auto; & > div:not(.gutter) { min-width: 25%; } & > .gutter { cursor: col-resize; } `; const TutorialPage = styled.div` ${({ theme }) => css` overflow: auto; max-width: 60rem; padding-top: ${theme.components.tabs.tab.default.height}; background: ${theme.components.main.primary.tutorial.default.bg}; `} `; const TutorialContent = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS( theme.components.main.primary.tutorial.tutorialPage )}; `} `; const NavigationButtonsOutsideWrapper = styled.div` padding: 3rem 0; `; const NavigationButtonsInsideWrapper = styled.div` ${({ theme }) => css` display: flex; width: 100%; padding-top: 1.5rem; border-top: 1px solid ${theme.colors.default.border}; font-size: ${theme.font.other.size.small}; font-weight: bold; `} `; const NavigationButton = styled(Button)` ${({ theme }) => css` margin-top: 0.5rem; font-size: ${theme.font.other.size.medium}; font-weight: bold; & svg { width: 1.25rem; height: 1.25rem; } `} `; const PreviousWrapper = styled.div` width: 100%; `; const PreviousText = styled.div``; const NextWrapper = styled.div` display: flex; flex-direction: column; align-items: flex-end; width: 100%; `; const NextText = styled.div``;
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Tutorial
solana_public_repos/solana-playground/solana-playground/client/src/components/Tutorial/views/index.ts
export { About } from "./About"; export { Main } from "./Main";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Tutorial
solana_public_repos/solana-playground/solana-playground/client/src/components/Tutorial/views/About.tsx
import { FC, Fragment } from "react"; import styled, { css } from "styled-components"; import Button from "../../Button"; import Link from "../../Link"; import Markdown from "../../Markdown"; import TutorialDetails from "../TutorialDetails"; import { PointedArrow, Triangle } from "../../Icons"; import { PgTheme, PgTutorial } from "../../../utils/pg"; import type { TutorialAboutComponentProps } from "../types"; export const About: FC<TutorialAboutComponentProps> = ({ files, defaultOpenFile, about, pages, }) => { const tutorial = PgTutorial.data; const isStarted = !!PgTutorial.pageNumber; const isFinished = PgTutorial.completed; const startTutorial = async () => { await PgTutorial.start({ files, defaultOpenFile, pageCount: pages.length, }); }; if (!tutorial) return null; return ( <Wrapper> <GoBackButtonWrapper> <Link href="/tutorials"> <Button kind="no-border" leftIcon={<PointedArrow rotate="180deg" />}> Go back to tutorials </Button> </Link> </GoBackButtonWrapper> <TutorialAboutPage> <GeneratedWrapper> <GeneratedTopWrapper> <GeneratedTopLeftWrapper> <TutorialName>{tutorial.name}</TutorialName> <TutorialAuthorsWrapper> <TutorialAuthorsByText>by </TutorialAuthorsByText> {tutorial.authors.length !== 0 && tutorial.authors.map((author, i) => ( <Fragment key={i}> {i !== 0 && ( <TutorialAuthorSeperator>, </TutorialAuthorSeperator> )} {author.link ? ( <TutorialAuthorLink href={author.link}> {author.name} </TutorialAuthorLink> ) : ( <TutorialAuthorWithoutLink> {author.name} </TutorialAuthorWithoutLink> )} </Fragment> ))} </TutorialAuthorsWrapper> </GeneratedTopLeftWrapper> <GeneratedTopRightWrapper> <Button onClick={startTutorial} kind={isFinished ? "no-border" : "secondary"} color={isFinished ? "success" : undefined} fontWeight="bold" leftIcon={ isFinished ? <span>✔</span> : <Triangle rotate="90deg" /> } > {isFinished ? "COMPLETED" : isStarted ? "CONTINUE" : "START"} </Button> </GeneratedTopRightWrapper> </GeneratedTopWrapper> <GeneratedBottomWrapper> <TutorialDescription>{tutorial.description}</TutorialDescription> <TutorialDetails details={[ { kind: "level", data: tutorial.level }, { kind: "framework", data: tutorial.framework }, { kind: "languages", data: tutorial.languages }, // TODO: Enable once there are more tutorials with various categories // { kind: "categories", data: tutorial.categories }, ]} /> </GeneratedBottomWrapper> </GeneratedWrapper> <CustomWrapper> {typeof about === "string" ? <Markdown>{about}</Markdown> : about} </CustomWrapper> </TutorialAboutPage> </Wrapper> ); }; const Wrapper = styled.div` height: 100%; width: 100%; overflow: auto; `; const GoBackButtonWrapper = styled.div` display: flex; align-items: center; height: ${({ theme }) => theme.components.tabs.tab.default.height}; padding-left: 1rem; & svg { width: 1.25rem; height: 1.25rem; } `; const TutorialAboutPage = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.main.primary.tutorial.aboutPage)}; `} `; const GeneratedWrapper = styled.div` padding: 1.5rem 0; `; const GeneratedTopWrapper = styled.div` display: flex; justify-content: space-between; align-items: center; `; const GeneratedTopLeftWrapper = styled.div``; const TutorialName = styled.h1``; const TutorialAuthorsWrapper = styled.div` ${({ theme }) => css` margin-top: 0.5rem; font-size: ${theme.font.other.size.small}; color: ${theme.colors.default.textSecondary}; `} `; const TutorialAuthorsByText = styled.span``; const TutorialAuthorSeperator = styled.span``; const TutorialAuthorLink = styled(Link)``; const TutorialAuthorWithoutLink = styled.span``; const GeneratedTopRightWrapper = styled.div``; const GeneratedBottomWrapper = styled.div` margin-top: 1.5rem; display: flex; flex-direction: column; gap: 1rem; `; const TutorialDescription = styled.p` color: ${({ theme }) => theme.colors.default.textSecondary}; line-height: 1.5; `; const CustomWrapper = styled.div``;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Loading/App.tsx
import styled from "styled-components"; import { ThreeDots } from "./ThreeDots"; export const AppLoading = () => ( <Wrapper> <ThreeDots /> </Wrapper> ); const Wrapper = styled.div` position: relative; height: 100vh; width: 100vw; & > :first-child { position: absolute; bottom: 1rem; left: 2rem; } `;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Loading/ThreeDots.tsx
import styled, { css, keyframes } from "styled-components"; interface ThreeDotsProps { width?: string; height?: string; distance?: string; } export const ThreeDots = styled.div<ThreeDotsProps>` ${({ theme, width = "0.5rem", height = "0.5rem", distance = "1rem" }) => css` --bg: ${theme.colors.default.primary}; --bg-fade: ${theme.colors.default.primary + theme.default.transparency.low}; --distance: ${distance}; position: relative; animation: ${animation} 1s infinite linear alternate; animation-delay: 0.5s; &, &::before, &::after { width: ${width}; height: ${height}; border-radius: ${theme.default.borderRadius}; background: var(--bg); } &::before, &::after { content: ""; position: absolute; top: 0; display: inline-block; animation: ${animation} 1s infinite alternate; } &::before { left: calc(var(--distance) * -1); animation-delay: 0s; } &::after { left: var(--distance); animation-delay: 1s; } `} `; const animation = keyframes` 0% { background: var(--bg); } 100% { background: var(--bg-fade); } `;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Loading/index.ts
export { Wormhole } from "./Wormhole"; export { Spinner, SpinnerWithBg, spinnerAnimation } from "./Spinner"; export { Skeleton } from "./Skeleton";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Loading/Wormhole.tsx
import { FC } from "react"; import styled, { css, keyframes } from "styled-components"; // in rem const DEFAULT_SIZE = 3; const DEFAULT_CIRCLE_COUNT = 8; interface WormholeProps { size?: number; circleCount?: number; } export const Wormhole: FC<WormholeProps> = ({ size = DEFAULT_SIZE, circleCount = DEFAULT_CIRCLE_COUNT, }) => { return ( <Wrapper> <CircleWrapper size={size}> {Array(circleCount) .fill(1) .map((v, i) => v + i) .map((i) => ( <Circle key={i} number={i} size={size} /> ))} </CircleWrapper> </Wrapper> ); }; const Wrapper = styled.div` width: 100%; display: flex; justify-content: center; align-items: center; `; interface CircleWrapperProps { size?: number; className?: string; } const CircleWrapper = styled.div<CircleWrapperProps>` position: relative; width: ${({ size }) => `${size}rem` ?? `${DEFAULT_SIZE}rem`}; height: ${({ size }) => `${size}rem` ?? `${DEFAULT_SIZE}rem`}; `; interface CircleProps { number: number; size: number; className?: string; } const Circle = styled.span<CircleProps>` ${({ size, number, theme }) => css` position: absolute; height: ${`${size * (1 - number / 10)}rem`}; width: ${`${size * (1 - number / 10)}rem`}; top: ${number * 0.7 * 2.5}%; left: ${number * 0.35 * 2.5}%; border: 2px solid ${theme.colors.default.primary}; border-bottom-color: transparent; border-top-color: transparent; border-radius: 50%; transition: all 2s ease 0s; animation: 1s linear ${(number * 0.2) / 1}s infinite normal none running ${circleAnimation}; `} `; const circleAnimation = keyframes` 0% {transform: rotate(0deg)} 50% {transform: rotate(180deg)} 100% {transform: rotate(360deg)} `;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Loading/Spinner.tsx
import { FC } from "react"; import styled, { css, keyframes } from "styled-components"; import { ClassName } from "../../constants"; import { PgTheme } from "../../utils/pg"; interface SpinnerWithBgProps extends SpinnerProps { loading: boolean; className?: string; } export const SpinnerWithBg: FC<SpinnerWithBgProps> = ({ loading, className, children, ...spinnerProps }) => ( <Wrapper className={`${className ?? ""} ${loading ? ClassName.LOADING : ""}`}> <Spinner className="spinner" {...spinnerProps} /> {children} </Wrapper> ); const Wrapper = styled.div` ${({ theme }) => css` width: 100%; height: 100%; position: relative; &::after { content: ""; position: absolute; inset: 0; width: 100%; height: 100%; background: #00000000; z-index: -1; transition: all ${theme.default.transition.duration.medium} ${theme.default.transition.type}; } & > .spinner { display: none; } &.${ClassName.LOADING} { &::after { z-index: 1; ${PgTheme.convertToCSS(theme.default.backdrop)}; } & > .spinner { display: block; position: absolute; inset: 0; margin: auto; z-index: 2; } } `} `; interface SpinnerProps { size?: string; } export const Spinner = styled.div<SpinnerProps>` ${({ size = "1rem", theme }) => css` &::after { content: ""; width: ${size}; height: ${size}; border: 4px solid transparent; border-top-color: ${theme.colors.default.primary}; border-right-color: ${theme.colors.default.primary}; position: absolute; inset: 0; margin: auto; border-radius: 50%; animation: ${spinnerAnimation} 0.5s linear infinite; } `} `; export const spinnerAnimation = keyframes` 0% {transform: rotate(0deg)} 100% {transform: rotate(360deg)} `;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Loading/Skeleton.tsx
import styled, { css, keyframes } from "styled-components"; import { PgTheme } from "../../utils/pg"; interface SkeletonProps { height?: string; width?: string; } export const Skeleton = styled.div<SkeletonProps>` ${({ theme, height = "1rem", width = "100%" }) => { const skeleton = theme.components.skeleton; return css` position: relative; overflow: hidden; z-index: 1; height: ${height}; width: ${width}; &::after { content: ""; display: block; position: absolute; top: 0; left: 0; right: 0; height: 100%; background-repeat: no-repeat; background-image: linear-gradient( 90deg, ${skeleton.bg}, ${skeleton.highlightColor}, ${skeleton.bg} ); transform: translateX(-100%); animation: ${skeletonAnimation} 1.25s ease-in-out infinite; } ${PgTheme.convertToCSS(skeleton)}; `; }} `; const skeletonAnimation = keyframes` 100% { transform: translateX(100%); } `;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/ErrorBoundary/index.ts
export { default } from "./ErrorBoundary";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/ErrorBoundary/Fallback.tsx
import { FC } from "react"; import Text from "../Text"; import { Sad } from "../Icons"; interface FallbackProps { /** Error that was thrown */ error: Error; } const Fallback: FC<FallbackProps> = ({ error }) => ( <Text kind="error" icon={<Sad />}> <div>There was an unexpected error!</div> {error.message && <div>Reason: {error.message}</div>} </Text> ); export default Fallback;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/ErrorBoundary/ErrorBoundary.tsx
import { Component, ErrorInfo, ReactNode } from "react"; import styled, { css } from "styled-components"; import Button from "../Button"; import Tooltip from "../Tooltip"; import Fallback from "./Fallback"; import { Refresh } from "../Icons"; interface Props { /** Node to render as children */ children?: ReactNode; /** Fallback node when there is an error */ Fallback?: (props: { error: Error }) => JSX.Element; } interface State { /** Error that was thrown */ error: Error | null; } class ErrorBoundary extends Component<Props, State> { /** * Derive the state from the given error. * * @param error error that was thrown * @returns the state */ static getDerivedStateFromError(error: Error): State { // Update state so the next render will show the fallback UI. return { error }; } /** State of the component */ state: State = { error: null }; /** * Callback to run when an error is caught. * * @param error error that was thrown * @param info information about the error, e.g. stack trace */ componentDidCatch(error: Error, info: ErrorInfo) { // Example `info.componentStack`: // in ComponentThatThrows (created by App) // in ErrorBoundary (created by App) // in div (created by App) // in App // There is no need to log the error because it's logged automatically } /** Render `fallback` if there is an error, `children` otherwise. */ render() { if (this.state.error) { const FbComponent = this.props.Fallback ?? Fallback; const FbElement = <FbComponent error={this.state.error} />; // Reset the state (without the error) in order to re-render const refresh = () => this.setState((s) => ({ ...s, error: null })); if (this.props.Fallback) { return ( <Wrapper iconOnly> {FbElement} <Tooltip element="Refresh"> <Button kind="icon" onClick={refresh}> <Refresh color="error" /> </Button> </Tooltip> </Wrapper> ); } return ( <Wrapper> {FbElement} <Button kind="secondary-transparent" leftIcon={<Refresh />} onClick={refresh} > Refresh </Button> </Wrapper> ); } return this.props.children; } } const Wrapper = styled.div<{ iconOnly?: boolean }>` ${({ iconOnly }) => css` display: flex; align-items: center; justify-content: center; flex-direction: ${iconOnly ? "row-reverse" : "column"}; gap: ${iconOnly ? "0.25rem" : "1rem"}; `} `; export default ErrorBoundary;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Foldable/index.ts
export { default } from "./Foldable";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Foldable/Foldable.tsx
import { FC, ReactNode, useCallback, useEffect, useRef, useState, Dispatch, SetStateAction, } from "react"; import styled from "styled-components"; import { ClassName } from "../../constants"; import { ShortArrow } from "../Icons"; interface FoldableProps { element: ReactNode; isOpen?: boolean; setIsOpen?: Dispatch<SetStateAction<boolean>>; } const Foldable: FC<FoldableProps> = ({ element, isOpen = false, setIsOpen, children, }) => { const [show, setShow] = useState(false); useEffect(() => { setShow(isOpen); }, [isOpen]); const handleClick = useCallback(() => { if (setIsOpen) setIsOpen((o) => !o); else setShow((s) => !s); }, [setIsOpen]); const clickWrapperRef = useRef<HTMLDivElement>(null); useEffect(() => { if (show) { clickWrapperRef.current?.classList.add(ClassName.OPEN); } else { clickWrapperRef.current?.classList.remove(ClassName.OPEN); } }, [show]); return ( <> <ClickElWrapper ref={clickWrapperRef} onClick={handleClick}> <ShortArrow /> {element} </ClickElWrapper> {show && <InsideWrapper>{children}</InsideWrapper>} </> ); }; const ClickElWrapper = styled.div` display: flex; align-items: center; justify-content: flex-start; width: fit-content; user-select: none; & svg:first-child { margin-right: 0.5rem; } &.${ClassName.OPEN} svg:first-child { transform: rotate(90deg); } &:hover { cursor: pointer; } `; const InsideWrapper = styled.div` margin-top: 0.5rem; `; export default Foldable;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/CodeBlock/highlight.ts
import { getHighlighter, Highlighter, Lang, renderToHtml, setCDN, setWasm, Theme, toShikiTheme, } from "shiki"; import type { IRawTheme } from "vscode-textmate"; import { OrString, PgCommon } from "../../utils/pg"; /** * Convert the given code to HTML. * * @param code code to highlight * @param lang code language or alias * @param theme TextMate theme * @returns highlighted HTML string */ export const highlight = async ( code: string, lang: OrString<Lang>, theme: IRawTheme ) => { await initializeHighlighter(); await Promise.all([loadLanguage(lang as Lang), loadTheme(theme)]); const tokens = highlighter.codeToThemedTokens(code, lang, theme.name); return renderToHtml(tokens, { bg: "inherit", themeName: theme.name }); }; /** `shiki` highlighter */ let highlighter: Highlighter; /** Whether the `highlighter` is being initialized */ let isInitializing = false; /** Get or create `shiki` highlighter. */ const initializeHighlighter = async () => { if (highlighter) return; if (isInitializing) { return await PgCommon.tryUntilSuccess(() => { if (!highlighter) throw new Error(); }, 100); } isInitializing = true; const responseWasm = await fetch( require("vscode-oniguruma/release/onig.wasm?resource") ); setWasm(responseWasm); setCDN("/"); // There is no way to not load a default theme. // See: https://github.com/shikijs/shiki/issues/473 // // We put an empty JSON file at `/themes/dracula.json` otherwise it fails. highlighter = await getHighlighter({ theme: "dracula", langs: [], paths: { languages: "grammars", themes: "themes", }, }); }; /** Load the given language if needed. */ const loadLanguage = async (lang: Lang) => { const isLoaded = highlighter.getLoadedLanguages().includes(lang); if (!isLoaded) await highlighter.loadLanguage(lang); }; /** Load the given theme if needed. */ const loadTheme = async (theme: IRawTheme) => { const isLoaded = highlighter.getLoadedThemes().includes(theme.name as Theme); if (!isLoaded) await highlighter.loadTheme(toShikiTheme(theme)); };
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/CodeBlock/index.ts
export { default } from "./CodeBlock"; export type { CodeBlockProps } from "./CodeBlock";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/CodeBlock/CodeBlock.tsx
import { useState } from "react"; import styled, { css, useTheme } from "styled-components"; import CopyButton from "../CopyButton"; import { highlight } from "./highlight"; import { PgTheme } from "../../utils/pg"; import { useAsyncEffect, useDifferentBackground } from "../../hooks"; export interface CodeBlockProps { /** Code */ children: string; /** Language or alias */ lang?: string; } const CodeBlock = ({ lang, children, ...props }: CodeBlockProps) => { const code = children; const { ref: wrapperRef } = useDifferentBackground<HTMLDivElement>(); const { ref: copyButtonWrapperRef } = useDifferentBackground<HTMLDivElement>(); return ( <Wrapper ref={wrapperRef} {...props}> <CopyButtonWrapper ref={copyButtonWrapperRef}> <CopyButton copyText={code} /> </CopyButtonWrapper> <Code lang={lang}>{code}</Code> </Wrapper> ); }; const Wrapper = styled.div` ${({ theme }) => css` position: relative; border-radius: ${theme.default.borderRadius}; & pre { border-radius: ${theme.default.borderRadius}; font-family: ${theme.font.code.family}; font-size: ${theme.font.code.size.medium}; overflow: auto; ${PgTheme.getScrollbarCSS()}; } & > :first-child { opacity: 0; transition: opacity ${theme.default.transition.duration.short} ${theme.default.transition.type}; } &:hover > :first-child { opacity: 1; } `} `; const CopyButtonWrapper = styled.div` ${({ theme }) => css` position: absolute; top: 0.5rem; right: 1rem; border-radius: ${theme.default.borderRadius}; box-shadow: ${theme.default.boxShadow}; & button { padding: 0.375rem; & > svg { width: 1.25rem; height: 1.25rem; } } `} `; const Code = ({ children, lang }: CodeBlockProps) => { const [html, setHtml] = useState(""); const theme = useTheme(); useAsyncEffect(async () => { if (lang) { const highlightedHtml = await highlight( children, lang, PgTheme.convertToTextMateTheme(theme) ); setHtml(highlightedHtml); } else { setHtml(""); } }, [children, lang, theme]); if (!html) return <pre>{children}</pre>; return <div dangerouslySetInnerHTML={{ __html: html }} />; }; export default CodeBlock;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/ImportButton/ImportButton.tsx
import { ChangeEvent, FC, useRef, useState } from "react"; import styled, { css } from "styled-components"; import Button, { ButtonKind } from "../Button"; interface ImportButtonProps { onImport: (ev: ChangeEvent<HTMLInputElement>) => Promise<void>; accept?: string; showImportText?: boolean; buttonKind?: ButtonKind; noButton?: boolean; dir?: boolean; } const ImportButton: FC<ImportButtonProps> = ({ onImport, accept, buttonKind = "outline", showImportText, noButton, dir, children, }) => { const inputRef = useRef<HTMLInputElement>(null); const [importText, setImportText] = useState(""); const handleClick = () => { inputRef.current?.click(); }; const handleChange = async (ev: ChangeEvent<HTMLInputElement>) => { await onImport(ev); const files = ev.target.files; if (!files?.length) setImportText(""); else setImportText(files[0].name); }; const dirProps = dir ? { webkitdirectory: "", mozdirectory: "", directory: "", multiple: true } : {}; return ( <Wrapper> <input ref={inputRef} type="file" onChange={handleChange} accept={accept} {...dirProps} /> {noButton ? ( <div onClick={handleClick}>{children}</div> ) : ( <Button kind={buttonKind} onClick={handleClick}> {children} </Button> )} {showImportText && importText && <ImportInfo>{importText}</ImportInfo>} </Wrapper> ); }; const Wrapper = styled.div` display: flex; align-items: center; & input[type="file"] { display: none; } & > div { width: 100%; } `; const ImportInfo = styled.span` ${({ theme }) => css` color: ${theme.colors.default.textSecondary}; font-size: ${theme.font.code.size.small}; margin-left: 0.5rem; `} `; export default ImportButton;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/ImportButton/index.ts
export { default } from "./ImportButton";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Input/index.ts
export { default } from "./Input"; export type { InputProps } from "./Input";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Input/Input.tsx
import { ComponentPropsWithoutRef, Dispatch, FocusEvent, forwardRef, SetStateAction, } from "react"; import styled, { css } from "styled-components"; import { ClassName } from "../../constants"; import { PgTheme } from "../../utils/pg"; type InputError = string | boolean | null; export interface InputProps extends ComponentPropsWithoutRef<"input"> { value: string; error?: InputError; setError?: Dispatch<SetStateAction<any>>; validator?: (value: string) => boolean | void; } const Input = forwardRef<HTMLInputElement, InputProps>( ({ className, error, setError, onChange, validator, ...props }, ref) => ( <> {typeof error === "string" && error && <ErrorText>{error}</ErrorText>} <StyledInput ref={ref} {...defaultInputProps} {...props} className={`${className} ${error ? ClassName.ERROR : ""}`} onChange={(ev) => { onChange?.(ev); // Validation if (validator) { const handleError = (err: InputError) => { if (setError) setError(err); if (err) ev.target.classList.add(ClassName.ERROR); else ev.target.classList.remove(ClassName.ERROR); }; try { if (validator(ev.target.value) === false) { handleError(true); } else { handleError(null); } } catch (err: any) { console.log("Validation error:", err.message); handleError(err.message); } } }} /> </> ) ); const ErrorText = styled.div` ${({ theme }) => css` color: ${theme.colors.state.error.color}; font-size: ${theme.font.code.size.small}; margin-bottom: 0.5rem; `} `; const StyledInput = styled.input<InputProps>` ${({ theme }) => css` &:disabled { background: ${theme.colors.state.disabled.bg}; color: ${theme.colors.state.disabled.color}; cursor: not-allowed; } &.${ClassName.ERROR} { outline-color: transparent; border-color: ${theme.colors.state.error.color}; } &.${ClassName.SUCCESS} { outline-color: transparent; border-color: ${theme.colors.state.success.color}; } ${PgTheme.convertToCSS(theme.components.input)}; `}} `; const defaultInputProps = { autoComplete: "off", fullWidth: true, onFocus: (e: FocusEvent<HTMLInputElement>) => { e.target.classList.add(ClassName.TOUCHED); }, }; export default Input;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Markdown/Markdown.tsx
import ReactMarkdown from "react-markdown"; import styled, { css } from "styled-components"; import remarkGfm from "remark-gfm"; import CodeBlock from "../CodeBlock"; import Link, { LinkProps } from "../Link"; import { PgTheme } from "../../utils/pg"; interface MarkdownProps { /** Markdown string */ children: string; /** Make all fonts the code font */ codeFontOnly?: boolean; } const Markdown = (props: MarkdownProps) => ( <StyledMarkdown remarkPlugins={[remarkGfm]} components={{ /** Links */ a: (props) => <Link {...(props as LinkProps)} />, /** Code blocks */ pre: (props) => { const codeProps = (props as any).children[0].props; const lang = codeProps.className?.split("-")?.at(1); const code = codeProps.children[0]; return <CodeBlock lang={lang}>{code}</CodeBlock>; }, }} {...props} /> ); const StyledMarkdown = styled(ReactMarkdown)<MarkdownProps>` ${({ theme, codeFontOnly }) => css` --border-radius: ${theme.default.borderRadius}; --color-prettylights-syntax-comment: #8b949e; --color-prettylights-syntax-constant: #79c0ff; --color-prettylights-syntax-entity: #d2a8ff; --color-prettylights-syntax-storage-modifier-import: #c9d1d9; --color-prettylights-syntax-entity-tag: #7ee787; --color-prettylights-syntax-keyword: #ff7b72; --color-prettylights-syntax-string: #a5d6ff; --color-prettylights-syntax-variable: #ffa657; --color-prettylights-syntax-brackethighlighter-unmatched: #f85149; --color-prettylights-syntax-invalid-illegal-text: #f0f6fc; --color-prettylights-syntax-invalid-illegal-bg: #8e1519; --color-prettylights-syntax-carriage-return-text: #f0f6fc; --color-prettylights-syntax-carriage-return-bg: #b62324; --color-prettylights-syntax-string-regexp: #7ee787; --color-prettylights-syntax-markup-list: #f2cc60; --color-prettylights-syntax-markup-heading: #1f6feb; --color-prettylights-syntax-markup-italic: #c9d1d9; --color-prettylights-syntax-markup-bold: #c9d1d9; --color-prettylights-syntax-markup-deleted-text: #ffdcd7; --color-prettylights-syntax-markup-deleted-bg: #67060c; --color-prettylights-syntax-markup-inserted-text: #aff5b4; --color-prettylights-syntax-markup-inserted-bg: #033a16; --color-prettylights-syntax-markup-changed-text: #ffdfb6; --color-prettylights-syntax-markup-changed-bg: #5a1e02; --color-prettylights-syntax-markup-ignored-text: #c9d1d9; --color-prettylights-syntax-markup-ignored-bg: #1158c7; --color-prettylights-syntax-meta-diff-range: #d2a8ff; --color-prettylights-syntax-brackethighlighter-angle: #8b949e; --color-prettylights-syntax-sublimelinter-gutter-mark: #484f58; --color-prettylights-syntax-constant-other-reference-link: #a5d6ff; --color-fg-default: ${theme.components.markdown.color}; --color-fg-muted: ${theme.colors.default.textSecondary}; --color-fg-subtle: #484f58; --color-canvas-default: ${theme.components.markdown.bg}; --color-canvas-subtle: ${theme.components.markdown.subtleBg}; --color-border-default: ${theme.colors.default.border}; --color-border-muted: ${theme.colors.default.border + theme.default.transparency.high}; --color-neutral-muted: ${theme.colors.state.hover.bg}; --color-accent-fg: ${theme.colors.default.primary}; --color-accent-emphasis: #1f6feb; --color-attention-subtle: rgba(187, 128, 9, 0.15); --color-danger-fg: #f85149; & { -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; margin: 0; line-height: 1.5; word-wrap: break-word; ${PgTheme.convertToCSS(theme.components.markdown)}; ${codeFontOnly && ` font-family: ${theme.font.code.family} !important; font-size: ${theme.font.code.size.medium} !important; `} } .octicon { display: inline-block; fill: currentColor; vertical-align: text-bottom; } h1:hover .anchor .octicon-link:before, h2:hover .anchor .octicon-link:before, h3:hover .anchor .octicon-link:before, h4:hover .anchor .octicon-link:before, h5:hover .anchor .octicon-link:before, h6:hover .anchor .octicon-link:before { width: 16px; height: 16px; content: " "; display: inline-block; background: currentColor; -webkit-mask-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' version='1.1' aria-hidden='true'><path fill-rule='evenodd' d='M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z'></path></svg>"); mask-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' version='1.1' aria-hidden='true'><path fill-rule='evenodd' d='M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z'></path></svg>"); } details, figcaption, figure { display: block; } summary { display: list-item; } [hidden] { display: none !important; } a { background: transparent; color: var(--color-accent-fg); text-decoration: none; } a:active, a:hover { outline-width: 0; } abbr[title] { border-bottom: none; text-decoration: underline dotted; } b, strong { font-weight: 600; } dfn { font-style: italic; } h1 { margin: 0.67em 0; font-weight: 600; padding-bottom: 0.3em; font-size: 2em; border-bottom: 1px solid var(--color-border-muted); } mark { background: var(--color-attention-subtle); color: var(--color-text-primary); } small { font-size: 90%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } img { border-style: none; max-width: 100%; box-sizing: content-box; background: var(--color-canvas-default); } code, kbd, pre, samp { font-family: monospace, monospace; font-size: 1em; } figure { margin: 1em 40px; } hr { box-sizing: content-box; overflow: hidden; background: transparent; border-bottom: 1px solid var(--color-border-muted); height: 0.25em; padding: 0; margin: 24px 0; background: var(--color-border-default); border: 0; } input { font: inherit; margin: 0; overflow: visible; font-family: inherit; font-size: inherit; line-height: inherit; } [type="button"], [type="reset"], [type="submit"] { -webkit-appearance: button; } [type="button"]::-moz-focus-inner, [type="reset"]::-moz-focus-inner, [type="submit"]::-moz-focus-inner { border-style: none; padding: 0; } [type="button"]:-moz-focusring, [type="reset"]:-moz-focusring, [type="submit"]:-moz-focusring { outline: 1px dotted ButtonText; } [type="checkbox"], [type="radio"] { box-sizing: border-box; padding: 0; } [type="number"]::-webkit-inner-spin-button, [type="number"]::-webkit-outer-spin-button { height: auto; } [type="search"] { -webkit-appearance: textfield; outline-offset: -2px; } [type="search"]::-webkit-search-cancel-button, [type="search"]::-webkit-search-decoration { -webkit-appearance: none; } ::-webkit-input-placeholder { color: inherit; opacity: 0.54; } ::-webkit-file-upload-button { -webkit-appearance: button; font: inherit; } a:hover { text-decoration: underline; } hr::before { display: table; content: ""; } hr::after { display: table; clear: both; content: ""; } table { border-spacing: 0; border-collapse: collapse; display: block; width: max-content; max-width: 100%; overflow: auto; } td, th { padding: 0; } details summary { cursor: pointer; } details:not([open]) > *:not(summary) { display: none !important; } kbd { display: inline-block; padding: 3px 5px; font: 11px ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace; line-height: 10px; color: var(--color-fg-default); vertical-align: middle; background: var(--color-canvas-subtle); border: solid 1px var(--color-neutral-muted); border-bottom-color: var(--color-neutral-muted); border-radius: var(--border-radius); box-shadow: inset 0 -1px 0 var(--color-neutral-muted); } h1, h2, h3, h4, h5, h6 { margin-top: 24px; margin-bottom: 16px; font-weight: 600; line-height: 1.25; } h2 { font-weight: 600; padding-bottom: 0.3em; font-size: 1.5em; border-bottom: 1px solid var(--color-border-muted); } h3 { font-weight: 600; font-size: 1.25em; } h4 { font-weight: 600; font-size: 1em; } h5 { font-weight: 600; font-size: 0.875em; } h6 { font-weight: 600; font-size: 0.85em; color: var(--color-fg-muted); } p { margin-top: 0; margin-bottom: 10px; } blockquote { margin: 0; padding: 0 1em; color: var(--color-fg-muted); border-left: 0.25em solid var(--color-border-default); } ul, ol { margin-top: 0; margin-bottom: 0; padding-left: 2em; } ol ol, ul ol { list-style-type: lower-roman; } ul ul ol, ul ol ol, ol ul ol, ol ol ol { list-style-type: lower-alpha; } dd { margin-left: 0; } tt, code { font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace; font-size: 12px; } pre { margin-top: 0; margin-bottom: 0; font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace; font-size: 12px; word-wrap: normal; } .octicon { display: inline-block; overflow: visible !important; vertical-align: text-bottom; fill: currentColor; } ::placeholder { color: var(--color-fg-subtle); opacity: 1; } input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { margin: 0; -webkit-appearance: none; appearance: none; } .pl-c { color: var(--color-prettylights-syntax-comment); } .pl-c1, .pl-s .pl-v { color: var(--color-prettylights-syntax-constant); } .pl-e, .pl-en { color: var(--color-prettylights-syntax-entity); } .pl-smi, .pl-s .pl-s1 { color: var(--color-prettylights-syntax-storage-modifier-import); } .pl-ent { color: var(--color-prettylights-syntax-entity-tag); } .pl-k { color: var(--color-prettylights-syntax-keyword); } .pl-s, .pl-pds, .pl-s .pl-pse .pl-s1, .pl-sr, .pl-sr .pl-cce, .pl-sr .pl-sre, .pl-sr .pl-sra { color: var(--color-prettylights-syntax-string); } .pl-v, .pl-smw { color: var(--color-prettylights-syntax-variable); } .pl-bu { color: var(--color-prettylights-syntax-brackethighlighter-unmatched); } .pl-ii { color: var(--color-prettylights-syntax-invalid-illegal-text); background: var(--color-prettylights-syntax-invalid-illegal-bg); } .pl-c2 { color: var(--color-prettylights-syntax-carriage-return-text); background: var(--color-prettylights-syntax-carriage-return-bg); } .pl-sr .pl-cce { font-weight: bold; color: var(--color-prettylights-syntax-string-regexp); } .pl-ml { color: var(--color-prettylights-syntax-markup-list); } .pl-mh, .pl-mh .pl-en, .pl-ms { font-weight: bold; color: var(--color-prettylights-syntax-markup-heading); } .pl-mi { font-style: italic; color: var(--color-prettylights-syntax-markup-italic); } .pl-mb { font-weight: bold; color: var(--color-prettylights-syntax-markup-bold); } .pl-md { color: var(--color-prettylights-syntax-markup-deleted-text); background: var(--color-prettylights-syntax-markup-deleted-bg); } .pl-mi1 { color: var(--color-prettylights-syntax-markup-inserted-text); background: var(--color-prettylights-syntax-markup-inserted-bg); } .pl-mc { color: var(--color-prettylights-syntax-markup-changed-text); background: var(--color-prettylights-syntax-markup-changed-bg); } .pl-mi2 { color: var(--color-prettylights-syntax-markup-ignored-text); background: var(--color-prettylights-syntax-markup-ignored-bg); } .pl-mdr { font-weight: bold; color: var(--color-prettylights-syntax-meta-diff-range); } .pl-ba { color: var(--color-prettylights-syntax-brackethighlighter-angle); } .pl-sg { color: var(--color-prettylights-syntax-sublimelinter-gutter-mark); } .pl-corl { text-decoration: underline; color: var(--color-prettylights-syntax-constant-other-reference-link); } [data-catalyst] { display: block; } g-emoji { font-family: "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-size: 1em; font-style: normal !important; font-weight: 400; line-height: 1; vertical-align: -0.075em; } g-emoji img { width: 1em; height: 1em; } ::before { display: table; content: ""; } ::after { display: table; clear: both; content: ""; } > *:first-child { margin-top: 0 !important; } > *:last-child { margin-bottom: 0 !important; } a:not([href]) { color: inherit; text-decoration: none; } .absent { color: var(--color-danger-fg); } .anchor { float: left; padding-right: 4px; margin-left: -20px; line-height: 1; } .anchor:focus { outline: none; } p, blockquote, ul, ol, dl, table, pre, details { margin-top: 0; margin-bottom: 16px; } blockquote > :first-child { margin-top: 0; } blockquote > :last-child { margin-bottom: 0; } sup > a::before { content: "["; } sup > a::after { content: "]"; } h1 .octicon-link, h2 .octicon-link, h3 .octicon-link, h4 .octicon-link, h5 .octicon-link, h6 .octicon-link { color: var(--color-fg-default); vertical-align: middle; visibility: hidden; } h1:hover .anchor, h2:hover .anchor, h3:hover .anchor, h4:hover .anchor, h5:hover .anchor, h6:hover .anchor { text-decoration: none; } h1:hover .anchor .octicon-link, h2:hover .anchor .octicon-link, h3:hover .anchor .octicon-link, h4:hover .anchor .octicon-link, h5:hover .anchor .octicon-link, h6:hover .anchor .octicon-link { visibility: visible; } h1 tt, h1 code, h2 tt, h2 code, h3 tt, h3 code, h4 tt, h4 code, h5 tt, h5 code, h6 tt, h6 code { padding: 0 0.2em; font-size: inherit; } ul.no-list, ol.no-list { padding: 0; list-style-type: none; } ol[type="1"] { list-style-type: decimal; } ol[type="a"] { list-style-type: lower-alpha; } ol[type="i"] { list-style-type: lower-roman; } div > ol:not([type]) { list-style-type: decimal; } ul ul, ul ol, ol ol, ol ul { margin-top: 0; margin-bottom: 0; } li > p { margin-top: 16px; } li + li { margin-top: 0.25em; } dl { padding: 0; } dl dt { padding: 0; margin-top: 16px; font-size: 1em; font-style: italic; font-weight: 600; } dl dd { padding: 0 16px; margin-bottom: 16px; } table th { font-weight: 600; } table th, table td { padding: 6px 13px; border: 1px solid var(--color-border-default); } table tr { background: var(--color-canvas-default); border-top: 1px solid var(--color-border-muted); } table tr:nth-child(2n) { background: var(--color-canvas-subtle); } table img { background: transparent; } img[align="right"] { padding-left: 20px; } img[align="left"] { padding-right: 20px; } .emoji { max-width: none; vertical-align: text-top; background: transparent; } span.frame { display: block; overflow: hidden; } span.frame > span { display: block; float: left; width: auto; padding: 7px; margin: 13px 0 0; overflow: hidden; border: 1px solid var(--color-border-default); } span.frame span img { display: block; float: left; } span.frame span span { display: block; padding: 5px 0 0; clear: both; color: var(--color-fg-default); } span.align-center { display: block; overflow: hidden; clear: both; } span.align-center > span { display: block; margin: 13px auto 0; overflow: hidden; text-align: center; } span.align-center span img { margin: 0 auto; text-align: center; } span.align-right { display: block; overflow: hidden; clear: both; } span.align-right > span { display: block; margin: 13px 0 0; overflow: hidden; text-align: right; } span.align-right span img { margin: 0; text-align: right; } span.float-left { display: block; float: left; margin-right: 13px; overflow: hidden; } span.float-left span { margin: 13px 0 0; } span.float-right { display: block; float: right; margin-left: 13px; overflow: hidden; } span.float-right > span { display: block; margin: 13px auto 0; overflow: hidden; text-align: right; } code, tt { padding: 0.2em 0.4em; margin: 0; font-size: 85%; background: var(--color-neutral-muted); border-radius: var(--border-radius); } code br, tt br { display: none; } del code { text-decoration: inherit; } pre code { font-size: 100%; } pre > code { padding: 0; margin: 0; word-break: normal; white-space: pre; background: transparent; border: 0; } .highlight { margin-bottom: 16px; } .highlight pre { margin-bottom: 0; word-break: normal; } .highlight pre, pre { padding: 16px; overflow: auto; font-size: 85%; line-height: 1.45; } pre code, pre tt { display: inline; padding: 0; margin: 0; overflow: visible; line-height: inherit; word-wrap: normal; border: 0; font-family: inherit; font-size: inherit; } .csv-data td, .csv-data th { padding: 5px; overflow: hidden; font-size: 12px; line-height: 1; text-align: left; white-space: nowrap; } .csv-data .blob-num { padding: 10px 8px 9px; text-align: right; background: var(--color-canvas-default); border: 0; } .csv-data tr { border-top: 0; } .csv-data th { font-weight: 600; background: var(--color-canvas-subtle); border-top: 0; } .footnotes { font-size: 12px; color: var(--color-fg-muted); border-top: 1px solid var(--color-border-default); } .footnotes ol { padding-left: 16px; } .footnotes li { position: relative; } .footnotes li:target::before { position: absolute; top: -8px; right: -8px; bottom: -8px; left: -24px; pointer-events: none; content: ""; border: 2px solid var(--color-accent-emphasis); border-radius: var(--border-radius); } .footnotes li:target { color: var(--color-fg-default); } .footnotes .data-footnote-backref g-emoji { font-family: monospace; } .task-list-item { list-style-type: none; } .task-list-item label { font-weight: 400; } .task-list-item.enabled label { cursor: pointer; } .task-list-item + .task-list-item { margin-top: 3px; } .task-list-item .handle { display: none; } .task-list-item-checkbox { margin: 0 0.2em 0.25em -1.6em; vertical-align: middle; } .contains-task-list:dir(rtl) .task-list-item-checkbox { margin: 0 -1.6em 0.25em 0.2em; } ::-webkit-calendar-picker-indicator { filter: invert(50%); } /* Custom */ height: fit-content; `} `; export default Markdown;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Markdown/index.ts
export { default } from "./Markdown";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd/Dnd.tsx
import Context from "./Context"; import Draggable from "./Draggable"; import Droppable from "./Droppable"; import Sortable from "./Sortable"; const Dnd = { Context, Draggable, Droppable, Sortable, }; export default Dnd;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd/index.ts
export { default } from "./Dnd"; export type { DragStartEvent, DragEndEvent } from "@dnd-kit/core";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd/Context/Context.tsx
import { FC } from "react"; import ReactDOM from "react-dom"; import { DndContext, MouseSensor, useSensor, useSensors, DndContextProps, DragOverlayProps, DragOverlay, } from "@dnd-kit/core"; interface ContextProps extends DndContextProps { dragOverlay?: DragOverlayProps & { Element: JSX.Element | null; portalContainer?: Element | null; }; } const Context: FC<ContextProps> = ({ dragOverlay, children, ...props }) => { const sensors = useSensors( useSensor(MouseSensor, { activationConstraint: { distance: 8, }, }) ); return ( <DndContext sensors={sensors} {...props}> {children} {dragOverlay && (dragOverlay.portalContainer ? ( ReactDOM.createPortal( <DragOverlay {...dragOverlay}>{dragOverlay.Element}</DragOverlay>, dragOverlay.portalContainer ) ) : ( <DragOverlay {...dragOverlay}>{dragOverlay.Element}</DragOverlay> ))} </DndContext> ); }; export default Context;
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd/Context/index.ts
export { default } from "./Context";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd/Droppable/Droppable.tsx
import { CSSProperties, FC, useEffect } from "react"; import { UniqueIdentifier, useDroppable } from "@dnd-kit/core"; interface DroppableProps { id: UniqueIdentifier; overStyle?: CSSProperties; onDragOver?: (ref: HTMLElement) => void; } const Droppable: FC<DroppableProps> = ({ id, overStyle, onDragOver, children, }) => { const { isOver, node, setNodeRef } = useDroppable({ id }); useEffect(() => { if (isOver && node.current) onDragOver?.(node.current); }, [isOver, node, onDragOver]); return ( <div ref={setNodeRef} style={isOver ? overStyle : undefined}> {children} </div> ); }; export default Droppable;
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd/Droppable/index.ts
export { default } from "./Droppable";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd/Draggable/Draggable.tsx
import { ForwardRefExoticComponent } from "react"; import { UniqueIdentifier, useDraggable, UseDraggableArguments, } from "@dnd-kit/core"; interface DraggableProps<P> { Item: ForwardRefExoticComponent<P>; itemProps: P; id: UniqueIdentifier; } const Draggable = <P,>({ Item, itemProps, id }: DraggableProps<P>) => { const { attributes, listeners, setNodeRef, isDragging } = useDraggable({ id, data: itemProps as UseDraggableArguments["data"], }); return ( <Item ref={setNodeRef} style={{ cursor: isDragging ? "grabbing" : "pointer" }} {...listeners} {...attributes} {...itemProps} /> ); }; export default Draggable;
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd/Draggable/index.ts
export { default } from "./Draggable";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd/Sortable/index.ts
export { default } from "./Sortable"; export type { SortableItemProvidedProps } from "./Sortable";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd
solana_public_repos/solana-playground/solana-playground/client/src/components/Dnd/Sortable/Sortable.tsx
import { Dispatch, ForwardRefExoticComponent, SetStateAction, useState, } from "react"; import { DragEndEvent, DragStartEvent, UniqueIdentifier } from "@dnd-kit/core"; import { arrayMove, horizontalListSortingStrategy, rectSortingStrategy, rectSwappingStrategy, SortableContext, useSortable, verticalListSortingStrategy, } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; import DndContext from "../Context"; interface SortableProps<P, I extends UniqueIdentifier> { items: I[]; setItems: Dispatch<SetStateAction<I[]>>; Item: ForwardRefExoticComponent<P>; getItemProps: (item: I, index: number) => P; strategy?: SortStrategy; } type SortStrategy = | "rect-sorting" | "rect-swapping" | "horizontal" | "vertical"; const Sortable = <P, I extends UniqueIdentifier>({ items, setItems, Item, getItemProps, strategy = "rect-sorting", }: SortableProps<P, I>) => { const [activeItemProps, setActiveItemProps] = useState<P | null>(null); const handleDragStart = (ev: DragStartEvent) => { const data = ev.active.data.current as any; if (data.sortable.index === -1) { // If an item is recently added to the `items` list, the internal DND // context state doesn't get updated sometimes. To solve this, we // override the internal state `data.sortable` from the most up-to-date // values. data.sortable.index = items.findIndex((item) => item === data.id); // Due to how the internals of `SortableContext` works, we set each value // one-by-one because directly setting `data.sortable.items = items` // doesn't work for (const [key, value] of Object.entries(items)) { data.sortable.items[key] = value; } } setActiveItemProps(data); }; const handleDragEnd = (ev: DragEndEvent) => { const { active, over } = ev; if (!over || active.id === over.id) return; setItems((items) => { const oldIndex = items.indexOf(active.id as I); const newIndex = items.indexOf(over.id as I); return arrayMove(items, oldIndex, newIndex); }); setActiveItemProps(null); }; return ( <DndContext dragOverlay={{ Element: activeItemProps && <Item isDragOverlay {...activeItemProps} />, }} onDragStart={handleDragStart} onDragEnd={handleDragEnd} > <SortableContext items={items} strategy={getSortingStrategy(strategy)}> {items.map((item, i) => ( <SortableItem key={item} id={item} Item={Item} {...getItemProps(item, i)} /> ))} </SortableContext> </DndContext> ); }; interface SortableItemProps<P> { id: UniqueIdentifier; Item: ForwardRefExoticComponent<P>; } const SortableItem = <P,>(props: SortableItemProps<P> & P) => { const { attributes, listeners, setNodeRef, transform, transition, isDragging, } = useSortable({ id: props.id, data: props }); return ( <props.Item ref={setNodeRef} style={{ position: "relative", zIndex: isDragging ? 1 : undefined, transform: CSS.Translate.toString(transform), transition, cursor: isDragging ? "grabbing" : "pointer", }} isDragging={isDragging} {...attributes} {...listeners} {...props} /> ); }; const getSortingStrategy = (strategy: SortStrategy) => { switch (strategy) { case "rect-sorting": return rectSortingStrategy; case "rect-swapping": return rectSwappingStrategy; case "horizontal": return horizontalListSortingStrategy; case "vertical": return verticalListSortingStrategy; } }; export interface SortableItemProvidedProps { isDragging: boolean; isDragOverlay: boolean; } export default Sortable;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Toast/index.ts
export { default } from "./Toast"; export type { ToastChildProps } from "./Toast";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Toast/Toast.tsx
import { useCallback } from "react"; import styled, { css } from "styled-components"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.min.css"; import { EventName } from "../../constants"; import { PgCommon, PgTheme } from "../../utils/pg"; import { useSetStatic } from "../../hooks"; export interface ToastChildProps { id: number; } const Toast = () => { const setToast = useCallback(({ Component, props }) => { const id = PgCommon.generateRandomInt(0, 2 ** 12); if (typeof Component === "function") { Component = <Component {...props?.componentProps} id={id} />; } toast(Component, { ...props?.options, toastId: id }); }, []); useSetStatic(setToast, EventName.TOAST_SET); useSetStatic(toast.dismiss, EventName.TOAST_CLOSE); return ( <StyledContainer position={toast.POSITION.BOTTOM_LEFT} closeOnClick={false} /> ); }; const StyledContainer = styled(ToastContainer)` ${({ theme }) => css` &&&.Toastify__toast-container { left: ${theme.components.sidebar.left.default.width}; } .Toastify__toast { ${PgTheme.convertToCSS(theme.components.toast.default)}; } .Toastify__progress-bar { ${PgTheme.convertToCSS(theme.components.toast.progress)}; } .Toastify__close-button--light { ${PgTheme.convertToCSS(theme.components.toast.closeButton)}; } `} `; export default Toast;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Checkbox/index.ts
export { default } from "./Checkbox";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Checkbox/Checkbox.tsx
import { ComponentPropsWithoutRef, FC, forwardRef, ReactNode } from "react"; import styled, { css } from "styled-components"; interface CheckBoxProps extends ComponentPropsWithoutRef<"input"> { /** Checkbox `label` to show */ label?: ReactNode; } const Checkbox: FC<CheckBoxProps> = forwardRef<HTMLInputElement, CheckBoxProps>( ({ onChange, defaultChecked, label, ...props }, ref) => ( <Label> <StyledCheckbox ref={ref} type="checkbox" onChange={onChange} defaultChecked={defaultChecked} {...props} /> {label && <LabelText>{label}</LabelText>} </Label> ) ); const Label = styled.label` ${({ theme }) => css` user-select: none; width: fit-content; display: flex; align-items: center; color: ${theme.colors.default.textSecondary}; font-size: ${theme.font.code.size.small}; transition: all ${theme.default.transition.type} ${theme.default.transition.duration.short}; &:hover { cursor: pointer; color: ${theme.colors.default.textPrimary}; } &:has(> input[type="checkbox"]:checked) { color: ${theme.colors.default.textPrimary}; } &:hover, &:has(> input[type="checkbox"]:checked) { & * { color: inherit; } } `} `; const StyledCheckbox = styled.input` accent-color: ${({ theme }) => theme.colors.default.primary}; &:hover { cursor: pointer; } `; const LabelText = styled.span` ${({ theme }) => css` margin-left: 0.5rem; transition: all ${theme.default.transition.type} ${theme.default.transition.duration.short}; `} `; export default Checkbox;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Terminal/Terminal.tsx
import { FC, useEffect, useMemo, useRef } from "react"; import styled, { css, useTheme } from "styled-components"; import "xterm/css/xterm.css"; import { EventName } from "../../constants"; import { useExposeStatic, useKeybind } from "../../hooks"; import { CommandManager, PgCommon, PgTerm, PgTerminal, PgTheme, } from "../../utils/pg"; interface TerminalProps { cmdManager: CommandManager; } const Terminal: FC<TerminalProps> = ({ cmdManager }) => { const terminalRef = useRef<HTMLDivElement>(null); const theme = useTheme(); // Create xterm const term = useMemo(() => { const xterm = theme.components.terminal.xterm; return new PgTerm(cmdManager, { convertEol: true, rendererType: "dom", fontFamily: theme.font.code.family, fontSize: 14, cursorBlink: xterm.cursor.blink, cursorStyle: xterm.cursor.kind, tabStopWidth: 4, theme: { foreground: xterm.textPrimary, brightBlack: xterm.textSecondary, black: xterm.textSecondary, brightMagenta: xterm.primary, brightCyan: xterm.secondary, brightGreen: xterm.success, brightRed: xterm.error, brightYellow: xterm.warning, brightBlue: xterm.info, selection: xterm.selectionBg, cursor: xterm.cursor.color, cursorAccent: xterm.cursor.accentColor, }, }); }, [theme, cmdManager]); useExposeStatic(term, EventName.TERMINAL_STATIC); // Open terminal useEffect(() => { if (terminalRef.current) { if (terminalRef.current.hasChildNodes()) { terminalRef.current.removeChild(terminalRef.current.childNodes[0]); } term.open(terminalRef.current); } }, [term]); // Handle resize useEffect(() => { const terminalEl = terminalRef.current!; const observer = new ResizeObserver( PgCommon.throttle(() => term.fit(), 200) ); observer.observe(terminalEl); return () => observer.unobserve(terminalEl); }, [term]); useKeybind("Ctrl+L", () => { if (PgTerminal.isFocused()) term.clear(); }); return <Wrapper ref={terminalRef} />; }; const Wrapper = styled.div` ${({ theme }) => css` ${PgTheme.getScrollbarCSS({ allChildren: true })}; ${PgTheme.convertToCSS(theme.components.terminal.default)}; & .xterm-viewport { background: inherit !important; width: 100% !important; } `} `; export default Terminal;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Terminal/index.ts
export { default } from "./Terminal";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/ProgressBar/ProgressBar.tsx
import { FC, useEffect, useRef } from "react"; import styled, { css, useTheme } from "styled-components"; import { PgTheme } from "../../utils/pg"; interface ProgressBarProps { value: number; } const ProgressBar: FC<ProgressBarProps> = ({ value }) => { const wrapperRef = useRef<HTMLDivElement>(null); const theme = useTheme(); // Hide progress bar when value is falsy value but still allow the animation useEffect(() => { if (wrapperRef.current) { wrapperRef.current.style.borderColor = value ? theme.colors.default.border : "transparent"; } // eslint-disable-next-line react-hooks/exhaustive-deps }, [value, theme.name]); return ( <Wrapper ref={wrapperRef}> <Indicator style={{ width: `${value.toString()}%` }} /> </Wrapper> ); }; const Wrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.progressbar.default)}; `} `; const Indicator = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.progressbar.indicator)}; `} `; export default ProgressBar;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/ProgressBar/index.ts
export { default } from "./ProgressBar";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/ModalBackdrop/ModalBackdrop.tsx
import { ReactElement, useCallback, useState } from "react"; import styled, { css } from "styled-components"; import { EventName } from "../../constants"; import { PgCommon, PgTheme, PgView } from "../../utils/pg"; import { useKeybind, useSetStatic } from "../../hooks"; const ModalBackdrop = () => { const [modal, setModal] = useState<ReactElement | null>(null); const setModalStatic = useCallback(({ Component, props }) => { if (typeof Component === "function") { Component = <Component {...props} />; } setModal(Component); }, []); useSetStatic( setModalStatic, PgCommon.getSendAndReceiveEventNames(EventName.MODAL_SET).send ); // Close modal on ESC useKeybind("Escape", PgView.closeModal); return modal ? <Wrapper>{modal}</Wrapper> : null; }; const Wrapper = styled.div` ${({ theme }) => css` position: absolute; width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; inset: 0; z-index: 3; ${PgTheme.convertToCSS(theme.components.modal.backdrop)}; `} `; export default ModalBackdrop;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/ModalBackdrop/index.ts
export { default } from "./ModalBackdrop";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/FadeIn/index.ts
export { default } from "./FadeIn";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/FadeIn/FadeIn.tsx
import styled, { css, keyframes } from "styled-components"; interface FadeInProps {} const FadeIn = styled.div<FadeInProps>` ${({ theme }) => css` animation: ${fadeIn} ${theme.default.transition.duration.short} ${theme.default.transition.type} forwards; `} `; const fadeIn = keyframes` 0% { opacity: 0 } 100% { opacity: 1 } `; export default FadeIn;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/ExportButton/ExportButton.tsx
import { FC } from "react"; import styled from "styled-components"; import Button, { ButtonKind } from "../Button"; import { PgCommon } from "../../utils/pg"; interface ExportButtonProps { href: string | object; fileName: string; buttonKind?: ButtonKind; noButton?: boolean; } const ExportButton: FC<ExportButtonProps> = ({ href, fileName, buttonKind = "outline", noButton = false, children, }) => ( <Wrapper href={PgCommon.getDataUrl(href)} download={fileName}> {noButton ? ( <div>{children}</div> ) : ( <Button kind={buttonKind}>{children}</Button> )} </Wrapper> ); const Wrapper = styled.a` width: fit-content; `; export default ExportButton;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/ExportButton/index.ts
export { default } from "./ExportButton";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Img/Img.tsx
import { ComponentPropsWithoutRef, forwardRef } from "react"; interface ImgProps extends ComponentPropsWithoutRef<"img"> { /** Whether to block cross origin source */ noCrossOrigin?: boolean; } const Img = forwardRef<HTMLImageElement, ImgProps>( ({ noCrossOrigin, ...props }, ref) => ( <img ref={ref} alt="" loading="lazy" crossOrigin={noCrossOrigin ? undefined : "anonymous"} {...props} /> ) ); export default Img;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Img/index.ts
export { default } from "./Img";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Popover/Popover.tsx
import { FC, ReactNode, useCallback, useEffect, useLayoutEffect, useRef, useState, } from "react"; import ReactDOM from "react-dom"; import styled, { css } from "styled-components"; import FadeIn from "../FadeIn"; import { Id } from "../../constants"; import { PgCommon, RequiredKey, ValueOf } from "../../utils/pg"; export interface PopoverProps { /** Popover element to show on trigger */ popEl?: ReactNode; /** Element to anchor to */ anchorEl?: HTMLElement; /** Where to place the popover element relative to the anchor point */ placement?: "top" | "right" | "bottom" | "left"; /** Element stacking context */ stackingContext?: "above-modal" | "below-modal"; /** Arrow pointing to the `anchorEl` from the `popEl` */ arrow?: { /** Arrow size in px */ size: number; }; /** Whether to show the pop-up on hover */ showOnHover?: boolean; /** * Whether to continue to show the pop-up when the mouse is out of the anchor * element but inside the pop-up element. */ continueToShowOnPopupHover?: boolean; /** The amount of miliseconds to hover before the pop-up is visible */ delay?: number; /** Always take full width of the `anchorEl` */ alwaysTakeFullWidth?: boolean; /** Max allowed with for the popover text */ maxWidth?: number | string; /** Whether to use secondary background color for the popover */ bgSecondary?: boolean; } const Popover: FC<PopoverProps> = ({ anchorEl, ...props }) => { return anchorEl ? ( <AnchoredPopover {...props} anchorEl={anchorEl} /> ) : ( <ChildPopover {...props} /> ); }; type AnchoredPopoverProps = RequiredKey<PopoverProps, "anchorEl">; const AnchoredPopover: FC<AnchoredPopoverProps> = ({ popEl, children, ...props }) => <CommonPopover {...props}>{popEl}</CommonPopover>; type ChildPopoverProps = Omit<PopoverProps, "anchorEl">; const ChildPopover: FC<ChildPopoverProps> = ({ popEl, children, ...props }) => { // Requires re-render on-mount to make sure `anchorRef.current` exists const [mounted, setMounted] = useState(false); useEffect(() => { setMounted(true); }, []); const anchorRef = useRef<HTMLDivElement>(null); return ( <Wrapper ref={anchorRef}> {children} {mounted && ( <CommonPopover {...props} anchorEl={anchorRef.current!}> {popEl} </CommonPopover> )} </Wrapper> ); }; const Wrapper = styled.div` width: fit-content; height: fit-content; display: flex; `; type CommonPopoverProps = RequiredKey<PopoverProps, "anchorEl">; const CommonPopover: FC<CommonPopoverProps> = ({ anchorEl, delay = 500, placement = "top", arrow = { size: 8 }, stackingContext = "above-modal", ...props }) => { const [isVisible, setIsVisible] = useState(false); const [position, setPosition] = useState<Position>({ x: 0, y: 0 }); const [relativeMidPoint, setRelativeMidPoint] = useState(0); const popoverRef = useRef<HTMLDivElement>(null); // Always show the popover inside the window const reposition = useCallback(() => { if (!popoverRef.current) return; const anchorRect = anchorEl.getBoundingClientRect(); let popoverRect = popoverRef.current.getBoundingClientRect(); switch (placement) { case "top": case "bottom": { // Mid-point of the popover and the anchor element should be the same const x = Math.max( 0, anchorRect.x + (anchorRect.width - popoverRect.width) / 2 ); const y = Math.max( 0, placement === "top" ? anchorRect.top - (popoverRect.height + arrow.size) : anchorRect.bottom + arrow.size ); setPosition({ x: Math.round(x + popoverRect.width) > window.innerWidth ? Math.round(window.innerWidth - popoverRect.width) : x, y, }); // Get the rect again because `setPosition` above could affect the result popoverRect = popoverRef.current.getBoundingClientRect(); if (popoverRect.left === 0) { const distanceToLeftEdge = anchorRect.left; const totalDistance = distanceToLeftEdge + anchorRect.width / 2; setRelativeMidPoint(totalDistance); } else if (Math.round(popoverRect.right) === window.innerWidth) { const distanceToRightEdge = window.innerWidth - anchorRect.right; const totalDistance = distanceToRightEdge + anchorRect.width / 2; setRelativeMidPoint(popoverRect.width - totalDistance); } else { setRelativeMidPoint(popoverRect.width / 2); } break; } case "right": case "left": { // Mid-point of the popover and the anchor element should be the same const x = Math.max( 0, placement === "left" ? anchorRect.left - (popoverRect.width + arrow.size) : anchorRect.right + arrow.size ); const y = Math.max( 0, anchorRect.y + (anchorRect.height - popoverRect.height) / 2 ); setPosition({ x, y: Math.round(y + popoverRect.height) > window.innerHeight ? Math.round(window.innerHeight - popoverRect.height) : y, }); // Get the rect again because `setPosition` above could affect the result popoverRect = popoverRef.current.getBoundingClientRect(); if (popoverRect.top === 0) { const distanceToTopEdge = anchorRect.top; const totalDistance = distanceToTopEdge + anchorRect.height / 2; setRelativeMidPoint(totalDistance); } else if (Math.round(popoverRect.bottom) === window.innerHeight) { const distanceToBottomEdge = popoverRect.height; const totalDistance = distanceToBottomEdge - anchorRect.height / 2; setRelativeMidPoint(totalDistance); } else { setRelativeMidPoint(popoverRect.height / 2); } } } }, [anchorEl, placement, arrow.size]); // Reposition on `maxWidth` or `isVisible` change useLayoutEffect(() => { if (isVisible) reposition(); }, [props.maxWidth, isVisible, reposition]); // Set popover and arrow position on resize useEffect(() => { if (!isVisible) return; const popoverEl = popoverRef.current; if (!popoverEl) return; const repositionResizeObserver = new ResizeObserver(reposition); repositionResizeObserver.observe(anchorEl); repositionResizeObserver.observe(popoverEl); return () => { repositionResizeObserver.unobserve(anchorEl); repositionResizeObserver.unobserve(popoverEl); }; }, [anchorEl, isVisible, reposition]); // Handle open useEffect(() => { if (props.showOnHover) { anchorEl.onmouseenter = (ev: MouseEvent) => { const el = ev.target as Element; if (el.contains(popoverRef.current)) return; let isInside = true; const handleOut = () => { isInside = false; }; anchorEl.addEventListener("mouseleave", handleOut); setTimeout(() => { if (isInside) setIsVisible(true); anchorEl.removeEventListener("mouseleave", handleOut); }, delay); }; } else { anchorEl.onmousedown = () => { setIsVisible(true); }; } }, [props.showOnHover, delay, anchorEl]); // Handle hide useEffect(() => { if (!isVisible) return; if (props.showOnHover) { const hideOnMoveOutside = PgCommon.throttle((ev: MouseEvent) => { if (!popoverRef.current) return; // Get the rect inside the callback because element size can change const anchorRect = getRoundedClientRect(anchorEl); const isInsideAnchorHorizontal = ev.x > anchorRect.left && ev.x < anchorRect.right; const isInsideAnchorVertical = ev.y > anchorRect.top && ev.y < anchorRect.bottom; const isInsideAnchor = isInsideAnchorHorizontal && isInsideAnchorVertical; if (isInsideAnchor) return; if (props.continueToShowOnPopupHover) { const popoverRect = getRoundedClientRect(popoverRef.current); let isAnchorAligned; let isInsidePopover; switch (placement) { case "top": isAnchorAligned = ev.y < anchorRect.bottom || (isInsideAnchorVertical && !isInsideAnchorHorizontal); isInsidePopover = ev.x > popoverRect.left && ev.x < popoverRect.right && ev.y > popoverRect.top && ev.y < popoverRect.bottom + arrow.size; break; case "bottom": isAnchorAligned = ev.y > anchorRect.top || (isInsideAnchorVertical && !isInsideAnchorHorizontal); isInsidePopover = ev.x > popoverRect.left && ev.x < popoverRect.right && ev.y > popoverRect.top - arrow.size && ev.y < popoverRect.bottom; break; case "left": isAnchorAligned = ev.x < anchorRect.left || (isInsideAnchorVertical && !isInsideAnchorHorizontal); isInsidePopover = ev.x > popoverRect.left && ev.x < popoverRect.right + arrow.size && ev.y > popoverRect.top && ev.y < popoverRect.bottom; break; case "right": isAnchorAligned = ev.x > anchorRect.right || (isInsideAnchorVertical && !isInsideAnchorHorizontal); isInsidePopover = ev.x > popoverRect.left - arrow.size && ev.x < popoverRect.right && ev.y > popoverRect.top && ev.y < popoverRect.bottom; } if (!(isAnchorAligned && isInsidePopover)) setIsVisible(false); } else { // Close outside of `anchorRect` if (!isInsideAnchor) setIsVisible(false); } }); const hideOnClick = () => { setIsVisible(false); }; const closeOutsideWindow = (ev: MouseEvent) => { if (ev.x < 0 || ev.y < 0) setIsVisible(false); }; document.addEventListener("mousemove", hideOnMoveOutside); anchorEl.addEventListener("mouseup", hideOnClick); anchorEl.addEventListener("mouseleave", closeOutsideWindow); return () => { document.removeEventListener("mousemove", hideOnMoveOutside); anchorEl.removeEventListener("mouseup", hideOnClick); anchorEl.removeEventListener("mouseleave", closeOutsideWindow); }; } else { // Ignore the initial open click because the initial open click also // triggers the `hide` callback run let isInitial = true; const hide = (ev: MouseEvent) => { if (isInitial) { isInitial = false; return; } const isOutside = !popoverRef.current?.contains(ev.target as Node); if (isOutside) setIsVisible(false); }; document.addEventListener("mousedown", hide); return () => document.removeEventListener("mousedown", hide); } }, [ isVisible, placement, anchorEl, arrow.size, props.showOnHover, props.continueToShowOnPopupHover, ]); // Handle always take full width useEffect(() => { if (!isVisible || !props.alwaysTakeFullWidth) return; const popoverEl = popoverRef.current; if (!popoverEl) return; const repositionResizeObserver = new ResizeObserver((entries) => { popoverEl.style.width = entries[0].contentRect.width + "px"; }); repositionResizeObserver.observe(anchorEl); return () => { repositionResizeObserver.unobserve(anchorEl); }; }, [props.alwaysTakeFullWidth, anchorEl, isVisible]); if (!isVisible) return null; return ReactDOM.createPortal( <StyledPopover ref={popoverRef} relativeMidPoint={relativeMidPoint} placement={placement} arrow={arrow} {...position} {...props} />, document.getElementById( stackingContext === "above-modal" ? Id.PORTAL_ABOVE : Id.PORTAL_BELOW )! ); }; interface Position { x: number; y: number; } const StyledPopover = styled(FadeIn)< Required<Pick<PopoverProps, "placement" | "arrow">> & Pick<PopoverProps, "alwaysTakeFullWidth" | "maxWidth" | "bgSecondary"> & Position & { relativeMidPoint: number } >` ${({ placement, arrow, x, y, relativeMidPoint, alwaysTakeFullWidth, maxWidth, bgSecondary, theme, }) => css` position: absolute; left: ${x}px; top: ${y}px; ${ !alwaysTakeFullWidth && `max-width: ${ !maxWidth ? "fit-content" : typeof maxWidth === "number" ? `${maxWidth}px` : maxWidth }` }; &::after { position: absolute; ${placement}: 100%; ${placement === "top" || placement === "bottom" ? "left" : "top"}: ${ relativeMidPoint - arrow.size }px; content: ""; border: ${arrow.size}px solid transparent; border-${placement}-color: ${ bgSecondary ? theme.components.tooltip.bgSecondary : theme.components.tooltip.bg }; pointer-events: none; } `} `; /** * Get the `DOMRect` of the given element with extra padding. * * @param el element to get the rect of * @returns the rounded `DOMRect` */ const getRoundedClientRect = (el: HTMLElement) => { type RoundedRect = Omit<DOMRect, "toJSON">; const addPadding = (key: keyof RoundedRect, value: ValueOf<RoundedRect>) => { const PADDING = 1; switch (key) { case "top": return value - PADDING; case "right": return value + PADDING; case "bottom": return value + PADDING; case "left": return value - PADDING; default: return value; } }; return PgCommon.entries( el.getBoundingClientRect().toJSON() as RoundedRect ).reduce((acc, [key, value]) => { acc[key] = Math.round(addPadding(key, value)); return acc; }, {} as { -readonly [K in keyof RoundedRect]: RoundedRect[K] }); }; export default Popover;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Popover/index.ts
export { default } from "./Popover"; export type { PopoverProps } from "./Popover";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/LangIcon/LangIcon.tsx
import { FC, useMemo } from "react"; import styled from "styled-components"; import { PgLanguage } from "../../utils/pg"; import { JavaScript, Json, Python, QuestionMark, Rust, TypeScript, } from "../Icons"; interface LangIconProps { /** File path to decide the language from */ path: string; } const LangIcon: FC<LangIconProps> = ({ path }) => { const Icon = useMemo(() => { const lang = PgLanguage.getFromPath(path); switch (lang?.name) { case "Rust": return <Rust color="textSecondary" />; case "Python": return <Python />; case "JavaScript": return <JavaScript isTest={path.endsWith(".test.js")} />; case "TypeScript": return <TypeScript isTest={path.endsWith(".test.ts")} />; case "JSON": return <Json />; default: return <QuestionMark />; } }, [path]); return <Wrapper>{Icon}</Wrapper>; }; const Wrapper = styled.div` width: 1rem; height: 1rem; & > svg, & > img { width: 100%; height: 100%; } `; export default LangIcon;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/LangIcon/index.ts
export { default } from "./LangIcon";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Button/index.ts
export { default } from "./Button"; export * from "./Button";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Button/Button.tsx
import { ComponentPropsWithoutRef, forwardRef, MouseEvent, ReactNode, useEffect, useState, } from "react"; import styled, { css, CSSProperties, DefaultTheme } from "styled-components"; import { spinnerAnimation } from "../Loading"; import { ClassName } from "../../constants"; import { PgTheme } from "../../utils/pg"; export type ButtonKind = | "primary" | "secondary" | "error" | "primary-transparent" | "secondary-transparent" | "primary-outline" | "secondary-outline" | "outline" | "transparent" | "no-border" | "icon"; export type ButtonSize = "small" | "medium" | "large"; type ButtonColor = | "primary" | "secondary" | "success" | "error" | "warning" | "info" | "textPrimary" | "textSecondary"; type ButtonBg = | "primary" | "secondary" | "success" | "error" | "warning" | "info"; export interface ButtonProps extends ComponentPropsWithoutRef<"button"> { /** Button kind */ kind?: ButtonKind; /** Button size */ size?: ButtonSize; /** Whether the button should take the full width of the parent element */ fullWidth?: boolean; /** Loading state */ btnLoading?: | boolean | { /** Whether the button is in loading state */ state?: boolean; /** Text to show when the button is in loading state */ text?: string; }; /** Left Icon */ leftIcon?: ReactNode; /** Right Icon */ rightIcon?: ReactNode; /** Background override */ bg?: ButtonBg; /** Color override */ color?: ButtonColor; /** Hover color override */ hoverColor?: ButtonColor; /** Font weight override */ fontWeight?: CSSProperties["fontWeight"]; } const Button = forwardRef<HTMLButtonElement, ButtonProps>( ( { btnLoading, className, disabled, leftIcon, rightIcon, onClick, children, ...props }, ref ) => { const [isLoading, setIsLoading] = useState(getIsLoading(btnLoading)); const [isDisabled, setIsDisabled] = useState(disabled); // Manage manual loading state useEffect(() => { const res = getIsLoading(btnLoading); if (res !== undefined) setIsLoading(res); }, [btnLoading]); // Disable when manually set or is loading useEffect(() => { setIsDisabled(disabled || isLoading); }, [disabled, isLoading]); const handleOnClick = async (ev: MouseEvent<HTMLButtonElement>) => { const shouldSetIsDisabled = getIsLoading(btnLoading) === undefined; const shouldSetIsLoading = shouldSetIsDisabled && props.kind !== "icon"; try { if (shouldSetIsDisabled) setIsDisabled(true); if (shouldSetIsLoading) setIsLoading(true); await onClick?.(ev); } finally { if (shouldSetIsDisabled) setIsDisabled(false); if (shouldSetIsLoading) setIsLoading(false); } }; return ( <StyledButton ref={ref} className={`${className} ${isLoading ? ClassName.BUTTON_LOADING : ""}`} disabled={isDisabled} onClick={handleOnClick} {...props} > <span className="btn-spinner" /> {leftIcon && <span className="left-icon">{leftIcon}</span>} {isLoading ? typeof btnLoading === "object" ? btnLoading.text ?? children : children : children} {rightIcon && <span className="right-icon">{rightIcon}</span>} </StyledButton> ); } ); /** Get whether the button is currently in a loading state */ const getIsLoading = (btnLoading: ButtonProps["btnLoading"]) => { return typeof btnLoading === "object" ? btnLoading.state : btnLoading; }; const StyledButton = styled.button<ButtonProps>` ${(props) => getButtonStyles(props)} `; const getButtonStyles = ({ theme, kind = "outline", size, fullWidth, bg: _bg, color: _color, hoverColor: _hoverColor, fontWeight: _fontWeight, }: ButtonProps & { theme: DefaultTheme }) => { // Clone the default Button theme to not override the global object let button = structuredClone(theme.components.button.default); // Kind switch (kind) { case "primary": { button.padding = "0.5rem 1.25rem"; button.bg = theme.colors.default.primary; button.hover!.bg = theme.colors.default.primary + "E0"; break; } case "secondary": { button.bg = theme.colors.default.secondary; button.hover!.bg = theme.colors.default.secondary + "E0"; button.padding = "0.5rem 1.25rem"; break; } case "primary-transparent": { button.padding = "0.5rem 1.25rem"; button.bg = theme.colors.default.primary + (theme.isDark ? theme.default.transparency.medium : theme.default.transparency.high); button.hover!.bg = theme.colors.default.primary + (theme.isDark ? theme.default.transparency.high : theme.default.transparency.medium); break; } case "secondary-transparent": { button.padding = "0.5rem 1.25rem"; button.bg = theme.colors.default.secondary + theme.default.transparency.medium; button.hover!.bg = theme.colors.default.secondary + theme.default.transparency.high; break; } case "error": { button.padding = "0.5rem 1.25rem"; button.bg = theme.colors.state.error.color + (theme.isDark ? theme.default.transparency.high : ""); button.hover!.bg = theme.colors.state.error.color + (theme.isDark ? "" : theme.default.transparency.high); break; } case "primary-outline": { button.borderColor = theme.colors.default.primary; button.hover!.bg = theme.colors.default.primary + "E0"; break; } case "secondary-outline": { button.borderColor = theme.colors.default.secondary; button.hover!.bg = theme.colors.default.secondary + "E0"; break; } case "outline": { button.borderColor = theme.colors.default.border; button.hover!.bg = theme.colors.state.hover.bg; button.hover!.borderColor = theme.colors.default.border; break; } case "icon": { button.padding = "0.25rem"; button.color = theme.colors.default.textSecondary; button.hover!.bg = theme.colors.state.hover.bg; button.hover!.color = theme.colors.default.textPrimary; break; } case "transparent": { button.padding = "0.5rem 0.75rem"; button.hover!.borderColor = theme.colors.default.border; break; } case "no-border": { button.padding = "0"; button.color = theme.colors.default.textSecondary; button.hover!.color = theme.colors.default.textPrimary; break; } } // Button kind specific overrides // NOTE: Overrides must come after setting the `ButtonKind` defaults button = PgTheme.overrideDefaults( button, theme.components.button.overrides?.[kind] ); // NOTE: Props must come after the defaults and overrides // Size prop if (size || !button.padding) { if (size === "large") button.padding = "0.75rem 1.5rem"; else if (size === "medium") button.padding = "0.5rem 1.25rem"; else if (size === "small") button.padding = "0.25rem 0.75rem"; else button.padding = "0.5rem 0.75rem"; } // Font weight prop if (_bg) { switch (_bg) { case "primary": button.bg = theme.colors.default.primary; break; case "secondary": button.bg = theme.colors.default.secondary; break; case "success": button.bg = theme.colors.state.success.bg; break; case "error": button.bg = theme.colors.state.error.bg; break; case "info": button.bg = theme.colors.state.info.bg; break; case "warning": button.bg = theme.colors.state.warning.bg; } } // Font weight prop if (_color) { switch (_color) { case "primary": button.color = theme.colors.default.primary + theme.default.transparency.high; button.hover!.color = theme.colors.default.primary; break; case "secondary": button.color = theme.colors.default.secondary + theme.default.transparency.high; button.hover!.color = theme.colors.default.secondary; break; case "success": button.color = theme.colors.state.success.color + theme.default.transparency.high; button.hover!.color = theme.colors.state.success.color; break; case "error": button.color = theme.colors.state.error.color + theme.default.transparency.high; button.hover!.color = theme.colors.state.error.color; break; case "info": button.color = theme.colors.state.info.color + theme.default.transparency.high; button.hover!.color = theme.colors.state.info.color; break; case "warning": button.color = theme.colors.state.warning.color + theme.default.transparency.high; button.hover!.color = theme.colors.state.warning.color; break; case "textPrimary": button.color = theme.colors.default.textPrimary; break; case "textSecondary": button.color = theme.colors.default.textSecondary; } } // Font weight prop if (_hoverColor) { switch (_hoverColor) { case "primary": button.hover!.color = theme.colors.default.primary; break; case "secondary": button.hover!.color = theme.colors.default.secondary; break; case "success": button.hover!.color = theme.colors.state.success.color; break; case "error": button.hover!.color = theme.colors.state.error.color; break; case "info": button.hover!.color = theme.colors.state.info.color; break; case "warning": button.hover!.color = theme.colors.state.warning.color; } } // Font weight prop if (_fontWeight) { button.fontWeight = _fontWeight; button.hover!.fontWeight = button.fontWeight; } let defaultCss = css` position: relative; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all ${theme.default.transition.duration.medium} ${theme.default.transition.type}; border: 1px solid ${button.borderColor}; ${PgTheme.convertToCSS(button)}; &:disabled { cursor: not-allowed; background: ${theme.colors.state.disabled.bg}; color: ${theme.colors.state.disabled.color}; &:hover { cursor: not-allowed; background: ${theme.colors.state.disabled.bg}; color: ${theme.colors.state.disabled.color}; } } /* Left Icon */ & > span.left-icon { display: flex; & > * { margin-right: 0.375rem; } } /* Right Icon */ & > span.right-icon { display: flex; & > * { margin-left: 0.375rem; } } /* Loading */ & > span.btn-spinner { transform: scale(0); } &.${ClassName.BUTTON_LOADING} > span.btn-spinner { width: 1rem; height: 1rem; margin-right: 0.5rem; border: 3px solid transparent; border-top-color: ${theme.colors.default.primary}; border-right-color: ${theme.colors.default.primary}; border-radius: 50%; animation: ${spinnerAnimation} 0.5s linear infinite; transform: scale(1); } `; if (fullWidth) { defaultCss = defaultCss.concat(css` width: 100%; `); } if (kind === "icon") { defaultCss = defaultCss.concat(css` height: fit-content; width: fit-content; & img, svg { width: 1rem; height: 1rem; } `); } return defaultCss; }; export default Button;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Link/Link.tsx
import { ComponentPropsWithoutRef, forwardRef } from "react"; import { Link as RouterLink } from "react-router-dom"; import styled, { css, DefaultTheme } from "styled-components"; import { External } from "../Icons"; import type { OrString } from "../../utils/pg"; export interface LinkProps extends ComponentPropsWithoutRef<"a"> { href: OrString<RoutePath>; } const Link = forwardRef<HTMLAnchorElement, LinkProps>((props, ref) => { const isWrapper = typeof props.children !== "string"; if (props.href.startsWith("/")) { return ( <StyledRouterLink ref={ref} to={props.href} {...props} $isWrapper={isWrapper} /> ); } return ( <StyledAnchor ref={ref} target="_blank" rel="noopener noreferrer" {...props} $isWrapper={isWrapper} > {props.children} {!isWrapper && <External />} </StyledAnchor> ); }); const getStyles = ({ $isWrapper, theme, }: { $isWrapper: boolean; theme: DefaultTheme; }) => { if ($isWrapper) { return css` & svg { color: ${theme.colors.default.textSecondary}; } & > * { transition: color ${theme.default.transition.duration.short} ${theme.default.transition.type}; &:hover { color: ${theme.colors.default.textPrimary}; } } `; } return css` color: ${theme.colors.default.primary}; border-bottom: 1px solid transparent; transition: border-bottom-color ${theme.default.transition.duration.short} ${theme.default.transition.type}; & svg { margin-left: 0.25rem; } &:hover { border-bottom-color: ${theme.colors.default.primary}; } `; }; const StyledAnchor = styled.a` ${getStyles} `; const StyledRouterLink = styled(RouterLink)` ${getStyles} `; export default Link;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Link/index.ts
export { default } from "./Link"; export type { LinkProps } from "./Link";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Delayed/index.ts
export { default } from "./Delayed";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Delayed/Delayed.tsx
import { FC, useEffect, useState } from "react"; interface DelayedProps { /** The amount of miliseconds to sleep before rendering the `children` */ delay?: number; } const Delayed: FC<DelayedProps> = ({ delay, children }) => { const [ready, setReady] = useState(false); useEffect(() => { const id = setTimeout(() => setReady(true), delay); return () => clearTimeout(id); }, [delay]); if (!ready) return null; return <>{children}</>; }; export default Delayed;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Icons/Icons.tsx
import styled, { css } from "styled-components"; import type { FC } from "react"; import type { SvgProperties } from "csstype"; import { PgTheme, ThemeColor } from "../../utils/pg"; interface IconProps { color?: ThemeColor; rotate?: "90deg" | "180deg" | "270deg"; } interface IconPropsInternal extends SvgProperties { viewBox: string; baseProfile?: string; } const defaultProps = { xmlns: "http://www.w3.org/2000/Svg", stroke: "currentColor", fill: "currentColor", strokeWidth: "0", width: "1em", height: "1em", }; /** `<Svg>` that works with `styled-components` and better defaults */ const Svg: FC<IconPropsInternal> = ({ children, ...props }) => ( <StyledSvg {...defaultProps} {...(props as {})}> {children} </StyledSvg> ); const StyledSvg = styled.svg<IconProps>` ${({ color, rotate }) => css` ${color && `color: ${PgTheme.getColor(color)}`}; ${rotate && `rotate: ${rotate}`}; `} `; export const ShortArrow = (props: IconProps) => ( <Svg {...props} viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0V0z"></path> <path d="M6.23 20.23L8 22l10-10L8 2 6.23 3.77 14.46 12z"></path> </Svg> ); export const LongArrow = (props: IconProps) => ( <Svg {...props} viewBox="0 0 16 16"> <path fillRule="evenodd" d="M1 8a.5.5 0 0 1 .5-.5h11.793l-3.147-3.146a.5.5 0 0 1 .708-.708l4 4a.5.5 0 0 1 0 .708l-4 4a.5.5 0 0 1-.708-.708L13.293 8.5H1.5A.5.5 0 0 1 1 8z" ></path> </Svg> ); export const PointedArrow = (props: IconProps) => ( <Svg {...props} viewBox="0 0 20 20"> <path fillRule="evenodd" d="M10.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L12.586 11H5a1 1 0 110-2h7.586l-2.293-2.293a1 1 0 010-1.414z" clipRule="evenodd" ></path> </Svg> ); export const DoubleArrow = (props: IconProps) => ( <Svg {...props} viewBox="0 0 320 512"> <path d="M177 255.7l136 136c9.4 9.4 9.4 24.6 0 33.9l-22.6 22.6c-9.4 9.4-24.6 9.4-33.9 0L160 351.9l-96.4 96.4c-9.4 9.4-24.6 9.4-33.9 0L7 425.7c-9.4-9.4-9.4-24.6 0-33.9l136-136c9.4-9.5 24.6-9.5 34-.1zm-34-192L7 199.7c-9.4 9.4-9.4 24.6 0 33.9l22.6 22.6c9.4 9.4 24.6 9.4 33.9 0l96.4-96.4 96.4 96.4c9.4 9.4 24.6 9.4 33.9 0l22.6-22.6c9.4-9.4 9.4-24.6 0-33.9l-136-136c-9.2-9.4-24.4-9.4-33.8 0z"></path> </Svg> ); export const Warning = (props: IconProps) => ( <Svg {...props} viewBox="0 0 1024 1024"> <path d="M955.7 856l-416-720c-6.2-10.7-16.9-16-27.7-16s-21.6 5.3-27.7 16l-416 720C56 877.4 71.4 904 96 904h832c24.6 0 40-26.6 27.7-48zM480 416c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v184c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V416zm32 352a48.01 48.01 0 0 1 0-96 48.01 48.01 0 0 1 0 96z"></path> </Svg> ); export const Close = (props: IconProps) => ( <Svg {...props} viewBox="0 0 512 512"> <path d="M289.94 256l95-95A24 24 0 00351 127l-95 95-95-95a24 24 0 00-34 34l95 95-95 95a24 24 0 1034 34l95-95 95 95a24 24 0 0034-34z"></path> </Svg> ); export const External = (props: IconProps) => ( <Svg {...props} fill="none" strokeWidth="2" viewBox="0 0 24 24" strokeLinecap="round" strokeLinejoin="round" > <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path> <polyline points="15 3 21 3 21 9"></polyline> <line x1="10" y1="14" x2="21" y2="3"></line> </Svg> ); export const Clear = (props: IconProps) => ( <Svg {...props} viewBox="0 0 1024 1024"> <defs></defs> <path d="M899.1 869.6l-53-305.6H864c14.4 0 26-11.6 26-26V346c0-14.4-11.6-26-26-26H618V138c0-14.4-11.6-26-26-26H432c-14.4 0-26 11.6-26 26v182H160c-14.4 0-26 11.6-26 26v192c0 14.4 11.6 26 26 26h17.9l-53 305.6c-0.3 1.5-0.4 3-0.4 4.4 0 14.4 11.6 26 26 26h723c1.5 0 3-0.1 4.4-0.4 14.2-2.4 23.7-15.9 21.2-30zM204 390h272V182h72v208h272v104H204V390z m468 440V674c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v156H416V674c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v156H202.8l45.1-260H776l45.1 260H672z"></path> </Svg> ); export const Tick = (props: IconProps) => ( <Svg {...props} baseProfile="tiny" viewBox="0 0 24 24"> <path d="M16.972 6.251c-.967-.538-2.185-.188-2.72.777l-3.713 6.682-2.125-2.125c-.781-.781-2.047-.781-2.828 0-.781.781-.781 2.047 0 2.828l4 4c.378.379.888.587 1.414.587l.277-.02c.621-.087 1.166-.46 1.471-1.009l5-9c.537-.966.189-2.183-.776-2.72z"></path> </Svg> ); export const Github = (props: IconProps) => ( <Svg {...props} viewBox="0 0 496 512"> <path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"></path> </Svg> ); export const Copy = (props: IconProps) => ( <Svg {...props} viewBox="0 0 24 24"> <path d="M20 2H10c-1.103 0-2 .897-2 2v4H4c-1.103 0-2 .897-2 2v10c0 1.103.897 2 2 2h10c1.103 0 2-.897 2-2v-4h4c1.103 0 2-.897 2-2V4c0-1.103-.897-2-2-2zM4 20V10h10l.002 10H4zm16-6h-4v-4c0-1.103-.897-2-2-2h-4V4h10v10z"></path> </Svg> ); export const Sad = (props: IconProps) => ( <Svg {...props} viewBox="0 0 24 24"> <path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm0 18c-4.411 0-8-3.589-8-8s3.589-8 8-8 8 3.589 8 8-3.589 8-8 8z"></path> <circle cx="8.5" cy="10.5" r="1.5"></circle> <circle cx="15.493" cy="10.493" r="1.493"></circle> <path d="M12 14c-3 0-4 3-4 3h8s-1-3-4-3z"></path> </Svg> ); export const Refresh = (props: IconProps) => ( <Svg {...props} viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0z"></path> <path d="M17.65 6.35A7.958 7.958 0 0012 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08A5.99 5.99 0 0112 18c-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"></path> </Svg> ); export const Error = (props: IconProps) => ( <Svg {...props} viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0z"></path> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"></path> </Svg> ); export const Info = (props: IconProps) => ( <Svg {...props} viewBox="0 0 1024 1024"> <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"></path> <path d="M464 336a48 48 0 1 0 96 0 48 48 0 1 0-96 0zm72 112h-48c-4.4 0-8 3.6-8 8v272c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V456c0-4.4-3.6-8-8-8z"></path> </Svg> ); export const Clock = (props: IconProps) => ( <Svg {...props} viewBox="0 0 1024 1024"> <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm176.5 585.7l-28.6 39a7.99 7.99 0 0 1-11.2 1.7L483.3 569.8a7.92 7.92 0 0 1-3.3-6.5V288c0-4.4 3.6-8 8-8h48.1c4.4 0 8 3.6 8 8v247.5l142.6 103.1c3.6 2.5 4.4 7.5 1.8 11.1z"></path> </Svg> ); export const ThreeDots = (props: IconProps) => ( <Svg {...props} viewBox="0 0 16 16"> <path d="M3 9.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z"></path> </Svg> ); export const Checkmark = (props: IconProps) => ( <Svg {...props} viewBox="0 0 512 512"> <path d="M256 48C141.6 48 48 141.6 48 256s93.6 208 208 208 208-93.6 208-208S370.4 48 256 48zm-42.7 318.9L106.7 260.3l29.9-29.9 76.8 76.8 162.1-162.1 29.9 29.9-192.1 191.9z"></path> </Svg> ); export const Plus = (props: IconProps) => ( <Svg {...props} viewBox="0 0 12 16"> <path fillRule="evenodd" d="M12 9H7v5H5V9H0V7h5V2h2v5h5v2z"></path> </Svg> ); export const PlusFilled = (props: IconProps) => ( <Svg {...props} viewBox="0 0 1024 1024"> <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm192 472c0 4.4-3.6 8-8 8H544v152c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V544H328c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h152V328c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v152h152c4.4 0 8 3.6 8 8v48z"></path> </Svg> ); export const MinusFilled = (props: IconProps) => ( <Svg {...props} viewBox="0 0 1024 1024"> <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm192 472c0 4.4-3.6 8-8 8H328c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h368c4.4 0 8 3.6 8 8v48z"></path> </Svg> ); export const Upload = (props: IconProps) => ( <Svg {...props} viewBox="0 0 512 512"> <path d="M403.002 217.001C388.998 148.002 328.998 96 256 96c-57.998 0-107.998 32.998-132.998 81.001C63.002 183.002 16 233.998 16 296c0 65.996 53.999 120 120 120h260c55 0 100-45 100-100 0-52.998-40.996-96.001-92.998-98.999zM288 276v76h-64v-76h-68l100-100 100 100h-68z"></path> </Svg> ); export const Edit = (props: IconProps) => ( <Svg {...props} viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0z"></path> <path d="M18.41 5.8L17.2 4.59c-.78-.78-2.05-.78-2.83 0l-2.68 2.68L3 15.96V20h4.04l8.74-8.74 2.63-2.63c.79-.78.79-2.05 0-2.83zM6.21 18H5v-1.21l8.66-8.66 1.21 1.21L6.21 18zM11 20l4-4h6v4H11z"></path> </Svg> ); export const Trash = (props: IconProps) => ( <Svg {...props} viewBox="0 0 448 512"> <path d="M432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16zM53.2 467a48 48 0 0 0 47.9 45h245.8a48 48 0 0 0 47.9-45L416 128H32z"></path> </Svg> ); export const ImportFile = (props: IconProps) => ( <Svg {...props} viewBox="0 0 512 512"> <path d="M16 288c-8.8 0-16 7.2-16 16v32c0 8.8 7.2 16 16 16h112v-64zm489-183L407.1 7c-4.5-4.5-10.6-7-17-7H384v128h128v-6.1c0-6.3-2.5-12.4-7-16.9zm-153 31V0H152c-13.3 0-24 10.7-24 24v264h128v-65.2c0-14.3 17.3-21.4 27.4-11.3L379 308c6.6 6.7 6.6 17.4 0 24l-95.7 96.4c-10.1 10.1-27.4 3-27.4-11.3V352H128v136c0 13.3 10.7 24 24 24h336c13.3 0 24-10.7 24-24V160H376c-13.2 0-24-10.8-24-24z"></path> </Svg> ); export const ExportFile = (props: IconProps) => ( <Svg {...props} viewBox="0 0 24 24"> <path d="M11 16h2V7h3l-4-5-4 5h3z"></path> <path d="M5 22h14c1.103 0 2-.897 2-2v-9c0-1.103-.897-2-2-2h-4v2h4v9H5v-9h4V9H5c-1.103 0-2 .897-2 2v9c0 1.103.897 2 2 2z"></path> </Svg> ); export const ImportWorkspace = (props: IconProps) => ( <Svg {...props} viewBox="0 0 1000 1000"> <g> <path d="M827.6,730.8c0,34.8-23.2,58-58,58H189.8c-34.8,0-58-29-58-58V429.3c0-23.2,11.6-40.6,29-52.2c17.4-46.4,40.6-87,69.6-127.6H184c-98.6,0-174,81.2-174,179.8v301.5c0,98.6,75.4,179.8,174,179.8h579.9c98.6,0,174-81.2,174-179.8V493.1l-116,87v150.8H827.6z M897.2,122c-174-81.2-382.7-5.8-463.9,174l-52.2-23.2c-17.4-11.6-46.4-5.8-58,5.8c-11.6,5.8-17.4,11.6-17.4,23.2c-5.8,11.6-5.8,23.2-5.8,34.8l58,289.9c5.8,17.4,17.4,34.8,34.8,40.6c17.4,5.8,34.8,5.8,52.2,0l255.1-139.2c11.6-5.8,17.4-17.4,23.2-29c5.8-5.8,5.8-17.4,5.8-29c0-23.2-11.6-40.6-34.8-52.2l-52.2-23.2c63.8-139.2,208.8-220.4,347.9-203C966.8,162.5,937.8,139.4,897.2,122z" /> </g> </Svg> ); export const Wrench = (props: IconProps) => ( <Svg {...props} viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0z" clipRule="evenodd"></path> <path d="M22.7 19l-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4z"></path> </Svg> ); export const Rocket = (props: IconProps) => ( <Svg {...props} viewBox="0 0 16 16"> <path d="M12.17 9.53c2.307-2.592 3.278-4.684 3.641-6.218.21-.887.214-1.58.16-2.065a3.578 3.578 0 0 0-.108-.563 2.22 2.22 0 0 0-.078-.23V.453c-.073-.164-.168-.234-.352-.295a2.35 2.35 0 0 0-.16-.045 3.797 3.797 0 0 0-.57-.093c-.49-.044-1.19-.03-2.08.188-1.536.374-3.618 1.343-6.161 3.604l-2.4.238h-.006a2.552 2.552 0 0 0-1.524.734L.15 7.17a.512.512 0 0 0 .433.868l1.896-.271c.28-.04.592.013.955.132.232.076.437.16.655.248l.203.083c.196.816.66 1.58 1.275 2.195.613.614 1.376 1.08 2.191 1.277l.082.202c.089.218.173.424.249.657.118.363.172.676.132.956l-.271 1.9a.512.512 0 0 0 .867.433l2.382-2.386c.41-.41.668-.949.732-1.526l.24-2.408Zm.11-3.699c-.797.8-1.93.961-2.528.362-.598-.6-.436-1.733.361-2.532.798-.799 1.93-.96 2.528-.361.599.599.437 1.732-.36 2.531Z"></path> <path d="M5.205 10.787a7.632 7.632 0 0 0 1.804 1.352c-1.118 1.007-4.929 2.028-5.054 1.903-.126-.127.737-4.189 1.839-5.18.346.69.837 1.35 1.411 1.925Z"></path> </Svg> ); export const RunAll = (props: IconProps) => ( <Svg {...props} viewBox="0 0 16 16"> <path d="M2.78 2L2 2.41v12l.78.42 9-6V8l-9-6zM3 13.48V3.35l7.6 5.07L3 13.48z"></path> <path fillRule="evenodd" clipRule="evenodd" d="M6 14.683l8.78-5.853V8L6 2.147V3.35l7.6 5.07L6 13.48v1.203z" ></path> </Svg> ); export const Airdrop = (props: IconProps) => ( <Svg {...props} viewBox="0 0 512 512"> <path d="M511.9 175c-9.1-75.6-78.4-132.4-158.3-158.7C390 55.7 416 116.9 416 192h28.1L327.5 321.5c-2.5-.6-4.8-1.5-7.5-1.5h-48V192h112C384 76.8 315.1 0 256 0S128 76.8 128 192h112v128h-48c-2.7 0-5 .9-7.5 1.5L67.9 192H96c0-75.1 26-136.3 62.4-175.7C78.5 42.7 9.2 99.5.1 175c-1.1 9.1 6.8 17 16 17h8.7l136.7 151.9c-.7 2.6-1.6 5.2-1.6 8.1v128c0 17.7 14.3 32 32 32h128c17.7 0 32-14.3 32-32V352c0-2.9-.9-5.4-1.6-8.1L487.1 192h8.7c9.3 0 17.2-7.8 16.1-17z"></path> </Svg> ); export const Triangle = (props: IconProps) => ( <Svg {...props} viewBox="0 0 512 512"> <path d="M256 32L20 464h472L256 32z"></path> </Svg> ); export const TestTube = (props: IconProps) => ( <Svg {...props} fill="none" strokeWidth="2" viewBox="0 0 24 24" strokeLinecap="round" strokeLinejoin="round" > <desc></desc> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M20 8.04l-12.122 12.124a2.857 2.857 0 1 1 -4.041 -4.04l12.122 -12.124"></path> <path d="M7 13h8"></path> <path d="M19 15l1.5 1.6a2 2 0 1 1 -3 0l1.5 -1.6z"></path> <path d="M15 3l6 6"></path> </Svg> ); export const TestPaper = (props: IconProps) => ( <Svg {...props} viewBox="0 0 297 297"> <g> <g> <path d="m206.51,32c-0.269-17.718-14.706-32-32.487-32h-49.379c-17.781,0-32.219,14.282-32.487,32h-42.657v265h198v-265h-40.99zm-81.866-16h49.189 0.19c9.099,0 16.5,7.402 16.5,16.5s-7.401,16.5-16.5,16.5h-49.379c-9.099,0-16.5-7.402-16.5-16.5s7.401-16.5 16.5-16.5zm23.856,239h-66v-16h66v16zm0-50h-66v-16h66v16zm0-49h-66v-16h66v16zm0-50h-66v-16h66v16zm43.768,160.029l-19.541-16.204 10.213-12.316 7.793,6.462 12.19-13.362 11.82,10.783-22.475,24.637zm0-50l-19.541-16.204 10.213-12.316 7.793,6.462 12.19-13.362 11.82,10.783-22.475,24.637zm0-49l-19.541-16.204 10.213-12.316 7.793,6.462 12.19-13.362 11.82,10.783-22.475,24.637zm0-50l-19.541-16.204 10.213-12.316 7.793,6.462 12.19-13.362 11.82,10.783-22.475,24.637z" /> </g> </g> </Svg> ); export const NewFile = (props: IconProps) => ( <Svg {...props} viewBox="0 0 1024 1024"> <path d="M480 580H372a8 8 0 0 0-8 8v48a8 8 0 0 0 8 8h108v108a8 8 0 0 0 8 8h48a8 8 0 0 0 8-8V644h108a8 8 0 0 0 8-8v-48a8 8 0 0 0-8-8H544V472a8 8 0 0 0-8-8h-48a8 8 0 0 0-8 8v108zm374.6-291.3c6 6 9.4 14.1 9.4 22.6V928c0 17.7-14.3 32-32 32H192c-17.7 0-32-14.3-32-32V96c0-17.7 14.3-32 32-32h424.7c8.5 0 16.7 3.4 22.7 9.4l215.2 215.3zM790.2 326L602 137.8V326h188.2z"></path> </Svg> ); export const NewFolder = (props: IconProps) => ( <Svg {...props} viewBox="0 0 1024 1024"> <path d="M880 298.4H521L403.7 186.2a8.15 8.15 0 0 0-5.5-2.2H144c-17.7 0-32 14.3-32 32v592c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V330.4c0-17.7-14.3-32-32-32zM632 577c0 3.8-3.4 7-7.5 7H540v84.9c0 3.9-3.2 7.1-7 7.1h-42c-3.8 0-7-3.2-7-7.1V584h-84.5c-4.1 0-7.5-3.2-7.5-7v-42c0-3.8 3.4-7 7.5-7H484v-84.9c0-3.9 3.2-7.1 7-7.1h42c3.8 0 7 3.2 7 7.1V528h84.5c4.1 0 7.5 3.2 7.5 7v42z"></path> </Svg> ); export const QuestionMark = (props: IconProps) => ( <Svg {...props} viewBox="0 0 16 16"> <path d="M3 4.075a.423.423 0 0 0 .43.44H4.9c.247 0 .442-.2.475-.445.159-1.17.962-2.022 2.393-2.022 1.222 0 2.342.611 2.342 2.082 0 1.132-.668 1.652-1.72 2.444-1.2.872-2.15 1.89-2.082 3.542l.005.386c.003.244.202.44.446.44h1.445c.247 0 .446-.2.446-.446v-.188c0-1.278.487-1.652 1.8-2.647 1.086-.826 2.217-1.743 2.217-3.667C12.667 1.301 10.393 0 7.903 0 5.645 0 3.17 1.053 3.001 4.075zm2.776 10.273c0 .95.758 1.652 1.8 1.652 1.085 0 1.832-.702 1.832-1.652 0-.985-.747-1.675-1.833-1.675-1.04 0-1.799.69-1.799 1.675z"></path> </Svg> ); export const Pause = (props: IconProps) => ( <Svg {...props} viewBox="0 0 512 512"> <path d="M96 448h106.7V64H96v384zM309.3 64v384H416V64H309.3z"></path> </Svg> ); export const QuestionMarkOutlined = (props: IconProps) => ( <Svg {...props} viewBox="0 0 16 16"> <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"></path> <path d="M5.255 5.786a.237.237 0 0 0 .241.247h.825c.138 0 .248-.113.266-.25.09-.656.54-1.134 1.342-1.134.686 0 1.314.343 1.314 1.168 0 .635-.374.927-.965 1.371-.673.489-1.206 1.06-1.168 1.987l.003.217a.25.25 0 0 0 .25.246h.811a.25.25 0 0 0 .25-.25v-.105c0-.718.273-.927 1.01-1.486.609-.463 1.244-.977 1.244-2.056 0-1.511-1.276-2.241-2.673-2.241-1.267 0-2.655.59-2.75 2.286zm1.557 5.763c0 .533.425.927 1.01.927.609 0 1.028-.394 1.028-.927 0-.552-.42-.94-1.029-.94-.584 0-1.009.388-1.009.94z"></path> </Svg> ); export const Eye = (props: IconProps) => ( <Svg {...props} viewBox="0 0 576 512"> <path d="M572.52 241.4C518.29 135.59 410.93 64 288 64S57.68 135.64 3.48 241.41a32.35 32.35 0 0 0 0 29.19C57.71 376.41 165.07 448 288 448s230.32-71.64 284.52-177.41a32.35 32.35 0 0 0 0-29.19zM288 400a144 144 0 1 1 144-144 143.93 143.93 0 0 1-144 144zm0-240a95.31 95.31 0 0 0-25.31 3.79 47.85 47.85 0 0 1-66.9 66.9A95.78 95.78 0 1 0 288 160z"></path> </Svg> ); export const Search = (props: IconProps) => ( <Svg {...props} viewBox="0 0 512 512"> <path d="M337.509 305.372h-17.501l-6.571-5.486c20.791-25.232 33.922-57.054 33.922-93.257C347.358 127.632 283.896 64 205.135 64 127.452 64 64 127.632 64 206.629s63.452 142.628 142.225 142.628c35.011 0 67.831-13.167 92.991-34.008l6.561 5.487v17.551L415.18 448 448 415.086 337.509 305.372zm-131.284 0c-54.702 0-98.463-43.887-98.463-98.743 0-54.858 43.761-98.742 98.463-98.742 54.7 0 98.462 43.884 98.462 98.742 0 54.856-43.762 98.743-98.462 98.743z"></path> </Svg> ); export const Rust = (props: IconProps) => ( <Svg {...props} viewBox="0 0 32 32"> <path d="M15.124,5.3a.832.832,0,1,1,.832.832h0a.831.831,0,0,1-.832-.832M5.2,12.834a.832.832,0,1,1,.832.832h0a.832.832,0,0,1-.832-.832m19.856.039a.832.832,0,1,1,.832.832.831.831,0,0,1-.832-.832h0M7.605,14.013a.76.76,0,0,0,.386-1l-.369-.835H9.074v6.545H6.144a10.247,10.247,0,0,1-.332-3.911Zm6.074.161V12.245h3.458c.179,0,1.261.206,1.261,1.016,0,.672-.83.913-1.513.913ZM8.958,24.561a.832.832,0,1,1,.832.832.831.831,0,0,1-.832-.832h0m12.331.039a.832.832,0,1,1,.832.832.832.832,0,0,1-.832-.832h0m.257-1.887a.758.758,0,0,0-.9.584l-.418,1.949a10.249,10.249,0,0,1-8.545-.041l-.417-1.949a.759.759,0,0,0-.9-.583h0l-1.721.37a10.233,10.233,0,0,1-.89-1.049h8.374c.095,0,.158-.017.158-.1V18.928c0-.086-.063-.1-.158-.1h-2.45V16.947h2.649a1.665,1.665,0,0,1,1.629,1.412c.105.413.336,1.757.494,2.187.157.483.8,1.447,1.482,1.447h4.323a10.243,10.243,0,0,1-.949,1.1Zm4.65-7.821a10.261,10.261,0,0,1,.022,1.779H25.167c-.105,0-.148.069-.148.172v.483c0,1.136-.641,1.384-1.2,1.447-.535.06-1.128-.224-1.2-.551a3.616,3.616,0,0,0-1.671-2.808c1.03-.654,2.1-1.619,2.1-2.911A3.292,3.292,0,0,0,21.44,9.8a4.559,4.559,0,0,0-2.2-.724H8.367A10.246,10.246,0,0,1,14.1,5.84l1.282,1.344a.758.758,0,0,0,1.072.026h0l1.434-1.372a10.248,10.248,0,0,1,7.015,5l-.982,2.217a.761.761,0,0,0,.386,1Zm2.448.036-.033-.343,1.011-.943a.42.42,0,0,0-.013-.595.428.428,0,0,0-.121-.081L28.2,12.483l-.1-.334.806-1.12a.422.422,0,0,0-.13-.581.43.43,0,0,0-.133-.055l-1.363-.222-.164-.306.573-1.257a.419.419,0,0,0-.236-.544.426.426,0,0,0-.146-.029l-1.383.048L25.7,7.819l.318-1.347a.421.421,0,0,0-.343-.487.435.435,0,0,0-.144,0L24.183,6.3l-.266-.219L23.966,4.7a.421.421,0,0,0-.431-.411.426.426,0,0,0-.141.028l-1.257.573-.306-.164-.222-1.363a.421.421,0,0,0-.5-.318.43.43,0,0,0-.133.055l-1.121.806-.333-.1-.483-1.293a.421.421,0,0,0-.555-.215.442.442,0,0,0-.12.08L17.418,3.39l-.343-.033L16.347,2.18a.421.421,0,0,0-.688,0l-.728,1.177-.343.033-.943-1.012a.421.421,0,0,0-.595.015.442.442,0,0,0-.08.12L12.483,3.8l-.333.1-1.12-.8a.422.422,0,0,0-.581.13.43.43,0,0,0-.055.133l-.222,1.363-.306.164L8.608,4.317a.421.421,0,0,0-.544.239.444.444,0,0,0-.028.144l.048,1.383L7.818,6.3,6.471,5.984a.421.421,0,0,0-.487.343.435.435,0,0,0,0,.144L6.3,7.819l-.218.265L4.7,8.036a.422.422,0,0,0-.383.573L4.89,9.866l-.164.306-1.363.222a.42.42,0,0,0-.318.5.43.43,0,0,0,.055.133l.806,1.12-.1.334-1.293.483a.421.421,0,0,0-.215.555.414.414,0,0,0,.081.121l1.011.943-.033.343-1.177.728a.421.421,0,0,0,0,.688l1.177.728.033.343-1.011.943a.421.421,0,0,0,.015.595.436.436,0,0,0,.119.08l1.293.483.1.334L3.1,20.972a.421.421,0,0,0,.131.581.43.43,0,0,0,.133.055l1.363.222.164.307-.573,1.257a.422.422,0,0,0,.24.545.438.438,0,0,0,.143.028l1.383-.048.219.266-.317,1.348a.42.42,0,0,0,.341.486.4.4,0,0,0,.146,0L7.818,25.7l.266.218L8.035,27.3a.419.419,0,0,0,.429.41.413.413,0,0,0,.143-.028l1.257-.573.306.164.222,1.362a.421.421,0,0,0,.5.319.407.407,0,0,0,.133-.055l1.12-.807.334.1.483,1.292a.422.422,0,0,0,.556.214.436.436,0,0,0,.119-.08l.943-1.011.343.034.728,1.177a.422.422,0,0,0,.588.1.413.413,0,0,0,.1-.1l.728-1.177.343-.034.943,1.011a.421.421,0,0,0,.595-.015.436.436,0,0,0,.08-.119l.483-1.292.334-.1,1.12.807a.421.421,0,0,0,.581-.131.43.43,0,0,0,.055-.133l.222-1.362.306-.164,1.257.573a.421.421,0,0,0,.544-.239.438.438,0,0,0,.028-.143l-.048-1.384.265-.218,1.347.317a.421.421,0,0,0,.487-.34.447.447,0,0,0,0-.146L25.7,24.183l.218-.266,1.383.048a.421.421,0,0,0,.41-.431.4.4,0,0,0-.028-.142l-.573-1.257.164-.307,1.363-.222a.421.421,0,0,0,.319-.5.434.434,0,0,0-.056-.135l-.806-1.12.1-.334,1.293-.483a.42.42,0,0,0,.215-.554.414.414,0,0,0-.081-.121l-1.011-.943.033-.343,1.177-.728a.421.421,0,0,0,0-.688Z" /> </Svg> ); export const Python = (props: IconProps) => ( <Svg {...props} viewBox="0 0 32 32"> <defs> <linearGradient id="a" x1="-133.268" y1="-202.91" x2="-133.198" y2="-202.84" gradientTransform="translate(25243.061 38519.17) scale(189.38 189.81)" gradientUnits="userSpaceOnUse" > <stop offset="0" stopColor="#387eb8" /> <stop offset="1" stopColor="#366994" /> </linearGradient> <linearGradient id="b" x1="-133.575" y1="-203.203" x2="-133.495" y2="-203.133" gradientTransform="translate(25309.061 38583.42) scale(189.38 189.81)" gradientUnits="userSpaceOnUse" > <stop offset="0" stopColor="#ffe052" /> <stop offset="1" stopColor="#ffc331" /> </linearGradient> </defs> <path d="M15.885,2.1c-7.1,0-6.651,3.07-6.651,3.07V8.36h6.752v1H6.545S2,8.8,2,16.005s4.013,6.912,4.013,6.912H8.33V19.556s-.13-4.013,3.9-4.013h6.762s3.772.06,3.772-3.652V5.8s.572-3.712-6.842-3.712h0ZM12.153,4.237a1.214,1.214,0,1,1-1.183,1.244v-.02a1.214,1.214,0,0,1,1.214-1.214h0Z" style={{ fill: "url(#a)" }} /> <path d="M16.085,29.91c7.1,0,6.651-3.08,6.651-3.08V23.65H15.985v-1h9.47S30,23.158,30,15.995s-4.013-6.912-4.013-6.912H23.64V12.4s.13,4.013-3.9,4.013H12.975S9.2,16.356,9.2,20.068V26.2s-.572,3.712,6.842,3.712h.04Zm3.732-2.147A1.214,1.214,0,1,1,21,26.519v.03a1.214,1.214,0,0,1-1.214,1.214h.03Z" style={{ fill: "url(#b)" }} /> </Svg> ); export const TypeScript = (props: IconProps & { isTest?: boolean }) => ( <Svg {...props} viewBox="0 0 32 32"> <path d="M23.827,8.243A4.424,4.424,0,0,1,26.05,9.524a5.853,5.853,0,0,1,.852,1.143c.011.045-1.534,1.083-2.471,1.662-.034.023-.169-.124-.322-.35a2.014,2.014,0,0,0-1.67-1c-1.077-.074-1.771.49-1.766,1.433a1.3,1.3,0,0,0,.153.666c.237.49.677.784,2.059,1.383,2.544,1.095,3.636,1.817,4.31,2.843a5.158,5.158,0,0,1,.416,4.333,4.764,4.764,0,0,1-3.932,2.815,10.9,10.9,0,0,1-2.708-.028,6.531,6.531,0,0,1-3.616-1.884,6.278,6.278,0,0,1-.926-1.371,2.655,2.655,0,0,1,.327-.208c.158-.09.756-.434,1.32-.761L19.1,19.6l.214.312a4.771,4.771,0,0,0,1.35,1.292,3.3,3.3,0,0,0,3.458-.175,1.545,1.545,0,0,0,.2-1.974c-.276-.395-.84-.727-2.443-1.422a8.8,8.8,0,0,1-3.349-2.055,4.687,4.687,0,0,1-.976-1.777,7.116,7.116,0,0,1-.062-2.268,4.332,4.332,0,0,1,3.644-3.374A9,9,0,0,1,23.827,8.243ZM15.484,9.726l.011,1.454h-4.63V24.328H7.6V11.183H2.97V9.755A13.986,13.986,0,0,1,3.01,8.289c.017-.023,2.832-.034,6.245-.028l6.211.017Z" style={{ fill: props.isTest ? "#e37933" : "#007acc" }} /> </Svg> ); export const JavaScript = (props: IconProps & { isTest?: boolean }) => ( <Svg {...props} viewBox="0 0 32 32"> <path d="M18.774,19.7a3.727,3.727,0,0,0,3.376,2.078c1.418,0,2.324-.709,2.324-1.688,0-1.173-.931-1.589-2.491-2.272l-.856-.367c-2.469-1.052-4.11-2.37-4.11-5.156,0-2.567,1.956-4.52,5.012-4.52A5.058,5.058,0,0,1,26.9,10.52l-2.665,1.711a2.327,2.327,0,0,0-2.2-1.467,1.489,1.489,0,0,0-1.638,1.467c0,1.027.636,1.442,2.1,2.078l.856.366c2.908,1.247,4.549,2.518,4.549,5.376,0,3.081-2.42,4.769-5.671,4.769a6.575,6.575,0,0,1-6.236-3.5ZM6.686,20c.538.954,1.027,1.76,2.2,1.76,1.124,0,1.834-.44,1.834-2.15V7.975h3.422V19.658c0,3.543-2.078,5.156-5.11,5.156A5.312,5.312,0,0,1,3.9,21.688Z" style={{ fill: props.isTest ? "#e37933" : "#f5de19" }} /> </Svg> ); export const Json = (props: IconProps) => ( <Svg {...props} viewBox="0 0 16 16"> <path fillRule="evenodd" clipRule="evenodd" color="#f5de19" d="M6 2.984V2h-.09c-.313 0-.616.062-.909.185a2.33 2.33 0 0 0-.775.53 2.23 2.23 0 0 0-.493.753v.001a3.542 3.542 0 0 0-.198.83v.002a6.08 6.08 0 0 0-.024.863c.012.29.018.58.018.869 0 .203-.04.393-.117.572v.001a1.504 1.504 0 0 1-.765.787 1.376 1.376 0 0 1-.558.115H2v.984h.09c.195 0 .38.04.556.121l.001.001c.178.078.329.184.455.318l.002.002c.13.13.233.285.307.465l.001.002c.078.18.117.368.117.566 0 .29-.006.58-.018.869-.012.296-.004.585.024.87v.001c.033.283.099.558.197.824v.001c.106.273.271.524.494.753.223.23.482.407.775.53.293.123.596.185.91.185H6v-.984h-.09c-.2 0-.387-.038-.563-.115a1.613 1.613 0 0 1-.457-.32 1.659 1.659 0 0 1-.309-.467c-.074-.18-.11-.37-.11-.573 0-.228.003-.453.011-.672.008-.228.008-.45 0-.665a4.639 4.639 0 0 0-.055-.64 2.682 2.682 0 0 0-.168-.609A2.284 2.284 0 0 0 3.522 8a2.284 2.284 0 0 0 .738-.955c.08-.192.135-.393.168-.602.033-.21.051-.423.055-.64.008-.22.008-.442 0-.666-.008-.224-.012-.45-.012-.678a1.47 1.47 0 0 1 .877-1.354 1.33 1.33 0 0 1 .563-.121H6zm4 10.032V14h.09c.313 0 .616-.062.909-.185.293-.123.552-.3.775-.53.223-.23.388-.48.493-.753v-.001c.1-.266.165-.543.198-.83v-.002c.028-.28.036-.567.024-.863-.012-.29-.018-.58-.018-.869 0-.203.04-.393.117-.572v-.001a1.502 1.502 0 0 1 .765-.787 1.38 1.38 0 0 1 .558-.115H14v-.984h-.09c-.196 0-.381-.04-.557-.121l-.001-.001a1.376 1.376 0 0 1-.455-.318l-.002-.002a1.415 1.415 0 0 1-.307-.465v-.002a1.405 1.405 0 0 1-.118-.566c0-.29.006-.58.018-.869a6.174 6.174 0 0 0-.024-.87v-.001a3.537 3.537 0 0 0-.197-.824v-.001a2.23 2.23 0 0 0-.494-.753 2.331 2.331 0 0 0-.775-.53 2.325 2.325 0 0 0-.91-.185H10v.984h.09c.2 0 .387.038.562.115.174.082.326.188.457.32.127.134.23.29.309.467.074.18.11.37.11.573 0 .228-.003.452-.011.672-.008.228-.008.45 0 .665.004.222.022.435.055.64.033.214.089.416.168.609a2.285 2.285 0 0 0 .738.955 2.285 2.285 0 0 0-.738.955 2.689 2.689 0 0 0-.168.602c-.033.21-.051.423-.055.64a9.15 9.15 0 0 0 0 .666c.008.224.012.45.012.678a1.471 1.471 0 0 1-.877 1.354 1.33 1.33 0 0 1-.563.121H10z" ></path> </Svg> );
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Icons/index.ts
export * from "./Icons";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/FilterGroups/FilterGroups.tsx
import { ComponentProps, FC } from "react"; import { useSearchParams } from "react-router-dom"; import styled, { css } from "styled-components"; import Checkbox from "../Checkbox"; import Tag from "../Tag"; import type { Arrayable } from "../../utils/pg"; interface FilterGroupsProps<P extends string> { filters: readonly { param: P; filters: readonly string[]; }[]; items?: Array<{ [K in P]?: Arrayable<string> }>; } const FilterGroups = <P extends string>({ filters, items, }: FilterGroupsProps<P>) => ( <> {filters.map((f) => ( <FilterGroup key={f.param} {...f} filters={f.filters.map((name) => ({ name, count: items?.filter((item) => { const field = item[f.param]; if (typeof field === "string") return field === name; if (Array.isArray(field)) return field.includes(name); return false; }).length, }))} /> ))} </> ); interface FilterGroupProps { param: string; filters: Array<{ name: string } & Pick<FilterLabelProps, "count">>; } const FilterGroup: FC<FilterGroupProps> = ({ param, filters }) => { const [searchParams, setSearchParams] = useSearchParams(); const searchValues = searchParams.getAll(param); return ( <FilterGroupWrapper> <FilterGroupTitle>{param}</FilterGroupTitle> {filters.filter(Boolean).map((filter) => ( <Checkbox key={filter.name} label={ <FilterLabel kind={param} value={filter.name} count={filter.count} /> } checked={searchValues.includes(filter.name)} onChange={(ev) => { if (ev.target.checked) { searchParams.append(param, filter.name); } else { const otherValues = searchValues.filter((f) => f !== filter.name); searchParams.delete(param); for (const otherValue of otherValues) { searchParams.append(param, otherValue); } } setSearchParams(searchParams, { replace: true }); }} /> ))} </FilterGroupWrapper> ); }; const FilterGroupWrapper = styled.div` padding: 1rem; & label { margin: 0.5rem 0; padding: 0.25rem; } `; const FilterGroupTitle = styled.div` ${({ theme }) => css` font-weight: bold; text-transform: uppercase; letter-spacing: 0.3px; font-size: ${theme.font.other.size.small}; `} `; type FilterLabelProps = ComponentProps<typeof Tag> & { count: number | undefined; }; const FilterLabel: FC<FilterLabelProps> = ({ count, ...props }) => ( <FilterLabelWrapper> <StyledTag {...props} /> {count ? <FilterCount>({count})</FilterCount> : null} </FilterLabelWrapper> ); const FilterLabelWrapper = styled.div` display: flex; align-items: center; gap: 0.125rem; `; const StyledTag = styled(Tag)` ${({ kind }) => { // Reset the default box styles except `level` if (kind !== "level") { return css` padding: 0 0.25rem; background: none !important; box-shadow: none; `; } }} `; const FilterCount = styled.span` font-weight: bold; `; export default FilterGroups;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/FilterGroups/index.ts
export { default } from "./FilterGroups";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Menu/MenuWrapper.tsx
import { ComponentPropsWithoutRef, forwardRef } from "react"; import styled, { css, DefaultTheme } from "styled-components"; import FadeIn from "../FadeIn"; import { Fn, PgTheme } from "../../utils/pg"; import { useKeybind } from "../../hooks"; import type { MenuKind } from "./Menu"; interface MenuWrapperProps extends ComponentPropsWithoutRef<"div"> { hide: Fn; kind: MenuKind; } export const MenuWrapper = forwardRef<HTMLDivElement, MenuWrapperProps>( ({ hide, ...props }, ref) => { useKeybind("Escape", hide); return <Wrapper ref={ref} {...props} />; } ); const Wrapper = styled(FadeIn)<Pick<MenuWrapperProps, "kind">>` ${(props) => getStyles(props)} `; const getStyles = ({ kind, theme, }: Pick<MenuWrapperProps, "kind"> & { theme: DefaultTheme }) => { const menu = PgTheme.overrideDefaults( theme.components.menu.default, theme.components.menu.overrides?.[kind] ); return css` ${PgTheme.convertToCSS(menu)}; `; };
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Menu/index.tsx
export { default } from "./Menu"; export type { MenuKind } from "./Menu"; export type { MenuItemProps } from "./MenuItem";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Menu/MenuItem.tsx
import { FC, ReactNode } from "react"; import styled, { css } from "styled-components"; import { PgTheme, ThemeColor } from "../../utils/pg"; export interface MenuItemProps { name: string; onClick: () => void; keybind?: string; color?: ThemeColor; hoverColor?: ThemeColor; icon?: ReactNode; showCondition?: boolean; className?: string; } enum ItemClassName { NAME = "item-name", KEYBIND = "item-keybind", } type MenuItemPropsWithHide = { hide: () => void; } & MenuItemProps; const MenuItem: FC<MenuItemPropsWithHide> = ({ name, onClick, hide, keybind, icon, showCondition = true, className, }) => { if (!showCondition) return null; const handleClick = () => { onClick(); hide?.(); }; return ( <div className={className} onClick={handleClick} onContextMenu={(ev) => { ev.stopPropagation(); ev.preventDefault(); handleClick(); }} > <div> {icon && icon} <span className={ItemClassName.NAME}>{name}</span> </div> {keybind && <span className={ItemClassName.KEYBIND}>{keybind}</span>} </div> ); }; const StyledItem = styled(MenuItem)` ${({ theme, color, hoverColor }) => css` padding: 0.5rem 1rem; display: flex; justify-content: space-between; align-items: center; font-weight: bold; font-size: ${theme.font.code.size.small}; color: ${PgTheme.getColor(color)}; border-left: 2px solid transparent; transition: all ${theme.default.transition.duration.short} ${theme.default.transition.type}; & > div { display: flex; align-items: center; min-width: max-content; } & svg { margin-right: 0.5rem; } & img { margin-right: 0.5rem; width: 1rem; height: 1rem; } & span.${ItemClassName.KEYBIND} { font-weight: normal; margin-left: 1.5rem; } &:hover { --color: ${PgTheme.getColor(hoverColor ?? "primary")}; cursor: pointer; background: ${theme.colors.state.hover.bg}; border-left-color: var(--color); & svg { color: var(--color); } & span.${ItemClassName.NAME} { color: var(--color); transition: all ${theme.default.transition.duration.short} ${theme.default.transition.type}; } } `} `; export default StyledItem;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Menu/ContextMenu.tsx
import { FC, MouseEvent, useCallback, useEffect, useLayoutEffect, useRef, useState, } from "react"; import ReactDOM from "react-dom"; import styled, { css } from "styled-components"; import MenuItem from "./MenuItem"; import { MenuWrapper } from "./MenuWrapper"; import { Id } from "../../constants"; import { useOnClickOutside } from "../../hooks"; import type { CommonMenuProps } from "./Menu"; // Circular dependency export type ContextMenuProps = { onContextMenu?: (ev: MouseEvent<HTMLDivElement>) => void; } & CommonMenuProps; type MenuState = | { state: "show"; position: Position; } | { state: "hide"; }; type Position = { x: number; y: number; }; const ContextMenu: FC<ContextMenuProps> = ({ items, onContextMenu, onShow, onHide, children, }) => { const [menu, setMenu] = useState<MenuState>({ state: "hide", }); const menuWrapperRef = useRef<HTMLDivElement>(null); const hide = useCallback(() => { setMenu({ state: "hide" }); }, []); const handleContextMenu = useCallback( (ev: MouseEvent<HTMLDivElement>) => { ev.preventDefault(); try { onContextMenu?.(ev); } catch { return; } setMenu({ state: "show", position: { x: ev.clientX, y: ev.clientY }, }); }, [onContextMenu] ); // Handle show or hide callbacks useEffect(() => { menu.state === "show" ? onShow?.() : onHide?.(); }, [menu.state, onShow, onHide]); // Always show the menu inside the window useLayoutEffect(() => { setMenu((menu) => { if (menu.state !== "show") return menu; const rect = menuWrapperRef.current!.getBoundingClientRect(); const extraWidth = rect.right - window.innerWidth; const extraHeight = rect.bottom - window.innerHeight; if (extraWidth > 0 || extraHeight > 0) { menu = structuredClone(menu); if (extraWidth > 0) menu.position.x -= extraWidth; if (extraHeight > 0) menu.position.y -= extraHeight; } return menu; }); }, [menu.state]); // Hide on outside click when the state is `show` useOnClickOutside(menuWrapperRef, hide, menu.state === "show"); return ( <Wrapper onContextMenu={handleContextMenu}> {children} {menu.state === "show" && ReactDOM.createPortal( <MenuWrapperWithPosition kind="context" ref={menuWrapperRef} hide={hide} {...menu.position} > {items.map((item, i) => ( <MenuItem key={i} {...item} hide={hide} /> ))} </MenuWrapperWithPosition>, document.getElementById(Id.PORTAL_ABOVE)! )} </Wrapper> ); }; const Wrapper = styled.div``; const MenuWrapperWithPosition = styled(MenuWrapper)<Position>` ${({ x, y }) => css` top: ${y}px; left: ${x}px; `} `; export default ContextMenu;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Menu/Menu.tsx
import ContextMenu from "./ContextMenu"; import DropdownMenu from "./DropdownMenu"; import type { MenuItemProps } from "./MenuItem"; import type { Fn } from "../../utils/pg"; export type MenuKind = "context" | "dropdown"; export type CommonMenuProps = { items: MenuItemProps[]; onShow?: Fn; onHide?: Fn; }; const Menu = { Context: ContextMenu, Dropdown: DropdownMenu, }; export default Menu;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Menu/DropdownMenu.tsx
import { FC, useCallback, useEffect, useRef, useState } from "react"; import styled from "styled-components"; import MenuItem from "./MenuItem"; import { MenuWrapper } from "./MenuWrapper"; import { useOnClickOutside } from "../../hooks"; import type { CommonMenuProps } from "./Menu"; // Circular dependency export type DropdownMenuProps = {} & CommonMenuProps; const DropdownMenu: FC<DropdownMenuProps> = ({ items, onShow, onHide, children, }) => { const [show, setShow] = useState(false); const toggle = useCallback(() => setShow((s) => !s), []); useEffect(() => { show ? onShow?.() : onHide?.(); }, [show, onShow, onHide]); const wrapperRef = useRef<HTMLDivElement>(null); // Close on outside click useOnClickOutside(wrapperRef, toggle, show); return ( <Wrapper ref={wrapperRef}> <ClickableWrapper onClick={toggle}>{children}</ClickableWrapper> {show && ( <StyledMenuWrapper kind="dropdown" hide={toggle}> {items.map((item, i) => ( <MenuItem key={i} {...item} hide={toggle} /> ))} </StyledMenuWrapper> )} </Wrapper> ); }; const Wrapper = styled.div` position: relative; `; const ClickableWrapper = styled.div``; const StyledMenuWrapper = styled(MenuWrapper)` min-width: 100%; `; export default DropdownMenu;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/Settings.tsx
import { FC } from "react"; import styled from "styled-components"; import Button from "../Button"; import Img from "../Img"; import Menu, { MenuItemProps } from "../Menu"; import { Airdrop, Copy, Edit, ExportFile, ImportFile, Plus, ThreeDots, Trash, } from "../Icons"; import { Fn, PgCommand, PgView, PgWallet } from "../../utils/pg"; import { useAirdrop, useDarken } from "./hooks"; import { useCopy } from "../../hooks"; interface SettingsProps { showRename: Fn; } const Settings: FC<SettingsProps> = ({ showRename }) => { const { airdrop, airdropCondition } = useAirdrop(); const { darken, lighten } = useDarken(); const [, copyAddress] = useCopy(PgWallet.current?.publicKey.toBase58()!); const isPg = !!PgWallet.current?.isPg; const defaultSettings: MenuItemProps[] = [ { name: "Copy address", onClick: copyAddress, icon: <Copy />, }, { name: "Airdrop", onClick: airdrop, showCondition: airdropCondition, icon: <Airdrop />, }, { name: "Add", onClick: async () => { const { Add } = await import("./Modals/Add"); await PgView.setModal(Add); }, icon: <Plus />, }, { name: "Rename", onClick: showRename, icon: <Edit />, showCondition: isPg, }, { name: "Remove", onClick: async () => { const { Remove } = await import("./Modals/Remove"); await PgView.setModal(Remove); }, hoverColor: "error", icon: <Trash />, showCondition: isPg, }, { name: "Import", onClick: PgWallet.import, icon: <ImportFile />, }, { name: "Export", onClick: PgWallet.export, icon: <ExportFile />, showCondition: isPg, }, ]; const standardWalletSettings: MenuItemProps[] = PgWallet.standardWallets.map( (wallet) => ({ name: wallet.adapter.connected ? `Disconnect from ${wallet.adapter.name}` : `Connect to ${wallet.adapter.name}`, onClick: () => PgCommand.connect.run(wallet.adapter.name), hoverColor: "secondary", icon: <Img src={wallet.adapter.icon} alt={wallet.adapter.name} />, }) ); return ( <Wrapper> <Menu.Dropdown items={defaultSettings.concat(standardWalletSettings)} onShow={darken} onHide={lighten} > <Button kind="icon" title="More"> <ThreeDots /> </Button> </Menu.Dropdown> </Wrapper> ); }; const Wrapper = styled.div` position: absolute; left: 1rem; `; export default Settings;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/Wallet.tsx
import { FC, useCallback, useEffect, useRef, useState } from "react"; import styled, { css } from "styled-components"; import { Rnd } from "react-rnd"; import Balance from "./Balance"; import Send from "./Send"; import Settings from "./Settings"; import Transactions from "./Transactions"; import Button from "../Button"; import FadeIn from "../FadeIn"; import Img from "../Img"; import Input from "../Input"; import Menu, { MenuItemProps } from "../Menu"; import Tooltip from "../Tooltip"; import { Close, ShortArrow } from "../Icons"; import { ClassName, Id } from "../../constants"; import { CurrentWallet, Fn, PgCommon, PgTheme, PgWallet } from "../../utils/pg"; import { useAutoAirdrop, useDarken, useStandardAccountChange, useSyncBalance, } from "./hooks"; import { useKeybind, useOnClickOutside, useRenderOnChange, useWallet, } from "../../hooks"; const Wallet = () => { useRenderOnChange(PgWallet.onDidChangeShow); const { wallet } = useWallet(); useStandardAccountChange(); useSyncBalance(); useAutoAirdrop(); if (!PgWallet.show || !wallet) return null; const tabHeight = document .getElementById(Id.TABS) ?.getBoundingClientRect().height; return ( <> <WalletBound id={Id.WALLET_BOUND} /> <Rnd default={{ x: window.innerWidth - (WALLET_WIDTH + 12), y: tabHeight ?? 32, width: "fit-content", height: "fit-content", }} minWidth={WALLET_WIDTH} maxWidth={WALLET_WIDTH} enableResizing={false} bounds={"#" + Id.WALLET_BOUND} enableUserSelectHack={false} style={{ zIndex: 1 }} > <WalletWrapper> <WalletTop /> <WalletMain /> </WalletWrapper> </Rnd> </> ); }; const WALLET_WIDTH = 320; const WalletBound = styled.div` ${({ theme }) => css` position: absolute; margin: ${theme.components.tabs.tab.default.height} 0.75rem ${theme.components.bottom.default.height} ${theme.components.sidebar.left.default.width}; width: calc( 100% - (0.75rem + ${theme.components.sidebar.left.default.width}) ); height: calc( 100% - ( ${theme.components.tabs.tab.default.height} + ${theme.components.bottom.default.height} ) ); z-index: -1; `} `; const WalletWrapper = styled(FadeIn)` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.wallet.default)}; `} `; const WalletTop = () => { const [rename, setRename] = useState(false); const showRename = useCallback(() => { setRename(true); }, []); const hideRename = useCallback(() => { setRename(false); }, []); return ( <WalletTopWrapper> <Settings showRename={showRename} /> {rename ? <WalletRename hideRename={hideRename} /> : <WalletName />} <WalletClose /> </WalletTopWrapper> ); }; const WalletTopWrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.wallet.top.default)}; `} `; const WalletName = () => { const { wallet } = useWallet(); const { darken, lighten } = useDarken(); const getAccountDisplayName = useCallback( (wallet: Pick<CurrentWallet, "name" | "publicKey">) => { return ( PgCommon.withMaxLength(wallet.name, 12) + ` - (${PgCommon.shorten(wallet.publicKey.toBase58())})` ); }, [] ); // Show al lof the Playground Wallet accounts const pgAccounts: MenuItemProps[] = PgWallet.accounts.map((acc, i) => ({ name: getAccountDisplayName(PgWallet.create(acc)), onClick: () => PgWallet.switch(i), hoverColor: "textPrimary", })); // Show all of the connected Wallet Standard accounts const standardAccounts: MenuItemProps[] = PgWallet.getConnectedStandardWallets().map((wallet) => ({ name: getAccountDisplayName(wallet), onClick: () => { PgWallet.update({ state: "sol", standardName: wallet.name }); }, icon: <Img src={wallet.icon} alt={wallet.name} />, hoverColor: "secondary", })); if (!wallet) return null; return ( <Menu.Dropdown items={pgAccounts.concat(standardAccounts)} onShow={darken} onHide={lighten} > <Tooltip element="Accounts"> <WalletTitleWrapper> {!wallet.isPg && ( <WalletTitleIcon src={wallet.icon} alt={wallet.name} /> )} <WalletTitleText>{getAccountDisplayName(wallet)}</WalletTitleText> <ShortArrow rotate="90deg" /> </WalletTitleWrapper> </Tooltip> </Menu.Dropdown> ); }; const WalletTitleWrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.wallet.top.title.default)}; `} `; const WalletTitleIcon = styled(Img)` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.wallet.top.title.icon)}; `} `; const WalletTitleText = styled.span` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.wallet.top.title.text)}; `} `; interface WalletRenameProps { hideRename: Fn; } const WalletRename: FC<WalletRenameProps> = ({ hideRename }) => { const [name, setName] = useState(PgWallet.current!.name); const inputRef = useRef<HTMLInputElement>(null); // Focus input on mount useEffect(() => { inputRef.current?.select(); }, []); // Close on outside clicks useOnClickOutside(inputRef, hideRename); // Keybinds useKeybind([ { keybind: "Enter", handle: () => { PgWallet.rename(name); hideRename(); }, }, { keybind: "Escape", handle: hideRename, }, ]); return ( <div> <Input ref={inputRef} value={name} onChange={(ev) => setName(ev.target.value)} validator={PgWallet.validateAccountName} placeholder="Rename wallet..." /> </div> ); }; const WalletClose = () => ( <CloseButton onClick={() => (PgWallet.show = false)} kind="icon"> <Close /> </CloseButton> ); const CloseButton = styled(Button)` position: absolute; right: 1rem; `; const WalletMain = () => ( <MainWrapper id={Id.WALLET_MAIN}> <Balance /> <Send /> <Transactions /> </MainWrapper> ); const MainWrapper = styled.div` ${({ theme }) => css` &::after { content: ""; width: 100%; height: 100%; position: absolute; inset: 0; background: #00000000; pointer-events: none; transition: all ${theme.default.transition.duration.short} ${theme.default.transition.type}; } &.${ClassName.DARKEN}::after { ${PgTheme.convertToCSS(theme.components.wallet.main.backdrop)}; } ${PgTheme.convertToCSS(theme.components.wallet.main.default)}; `} `; export default Wallet;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/Transactions.tsx
import { FC, useCallback, useEffect, useState } from "react"; import styled, { css } from "styled-components"; import Button from "../Button"; import Link from "../Link"; import { Clock, Refresh, Sad, Error as ErrorIcon } from "../Icons"; import { SpinnerWithBg } from "../Loading"; import { PgCommon, PgTheme, PgWallet, PgWeb3 } from "../../utils/pg"; import { useBlockExplorer, useConnection } from "../../hooks"; const Transactions = () => { const [signatures, setSignatures] = useState<PgWeb3.ConfirmedSignatureInfo[]>(); const [refreshCount, setRefreshCount] = useState(0); const [loading, setLoading] = useState(true); const [error, setError] = useState(false); const { connection } = useConnection(); useEffect(() => { const { dispose } = PgWallet.onDidChangeCurrent(async (wallet) => { setLoading(true); try { const _signatures = await PgCommon.transition( connection.getSignaturesForAddress(wallet!.publicKey, { limit: 10 }) ); setSignatures(_signatures); setError(false); } catch { setError(true); setSignatures([]); } finally { setLoading(false); } }); return dispose; }, [connection, refreshCount]); const refresh = useCallback(() => { setRefreshCount((c) => c + 1); }, []); // Refresh transactions every 30s useEffect(() => { const intervalId = setInterval(() => { refresh(); }, 30000); return () => clearInterval(intervalId); }, [refresh]); return ( <TxsWrapper> <TxsTitleWrapper> <TxsTitleText>Transactions</TxsTitleText> <TxsRefreshButton kind="icon" title="Refresh" onClick={refresh}> <Refresh /> </TxsRefreshButton> </TxsTitleWrapper> <TxsTable> <TxsTableHeader> <Signature>Signature</Signature> <Slot>Slot</Slot> <Time> Time <Clock /> </Time> </TxsTableHeader> <SpinnerWithBg loading={loading}> {signatures?.length ? ( signatures.map((info, i) => <Tx key={i} {...info} />) ) : ( <NoTransaction> {!loading && (error ? ( <> <Sad /> Connection error. </> ) : ( <> <Sad /> No transaction found. </> ))} </NoTransaction> )} </SpinnerWithBg> </TxsTable> </TxsWrapper> ); }; const TxsWrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.wallet.main.transactions.default)}; `} `; const TxsTitleWrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS( theme.components.wallet.main.transactions.title.default )}; `} `; const TxsTitleText = styled.span` ${({ theme }) => css` ${PgTheme.convertToCSS( theme.components.wallet.main.transactions.title.text )}; `} `; const TxsRefreshButton = styled(Button)` ${({ theme }) => css` ${PgTheme.convertToCSS( theme.components.wallet.main.transactions.title.refreshButton )}; `} `; const TxsTable = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS( theme.components.wallet.main.transactions.table.default )}; `} `; const TxsTableHeader = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS( theme.components.wallet.main.transactions.table.header )}; `} `; const NoTransaction = styled.div` padding: 2rem; display: flex; align-items: center; justify-content: center; color: ${({ theme }) => theme.colors.default.textSecondary}; & > svg { margin-right: 0.5rem; width: 1.5rem; height: 1.5rem; } `; const Tx: FC<PgWeb3.ConfirmedSignatureInfo> = ({ signature, slot, err, blockTime, }) => { const [hover, setHover] = useState(false); const enter = useCallback(() => setHover(true), []); const leave = useCallback(() => setHover(false), []); const now = new Date().getTime() / 1000; const timePassed = blockTime ? PgCommon.secondsToTime(now - blockTime) : null; const blockExplorer = useBlockExplorer(); return ( <TxWrapper onMouseEnter={enter} onMouseLeave={leave}> {hover ? ( <HoverWrapper> <Link href={blockExplorer.getTxUrl(signature)}> {blockExplorer.name} </Link> </HoverWrapper> ) : ( <> <Signature> {err && <ErrorIcon color="error" />} {signature.substring(0, 5)}... </Signature> <Slot>{slot}</Slot> {timePassed && <Time>{timePassed}</Time>} </> )} </TxWrapper> ); }; const TxWrapper = styled.div` ${({ theme }) => css` &:not(:last-child) { border-bottom: 1px solid ${theme.colors.default.border}; } & > div { height: 1rem; } ${PgTheme.convertToCSS( theme.components.wallet.main.transactions.table.row.default )}; `} `; const HoverWrapper = styled.div` display: flex; justify-content: space-around; width: 100%; `; const Signature = styled.div` ${({ theme }) => css` & > svg { margin-right: 0.25rem; } ${PgTheme.convertToCSS( theme.components.wallet.main.transactions.table.row.signature )}; `} `; const Slot = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS( theme.components.wallet.main.transactions.table.row.slot )}; `} `; const Time = styled.div` ${({ theme }) => css` & > svg { margin-left: 0.25rem; } ${PgTheme.convertToCSS( theme.components.wallet.main.transactions.table.row.time )}; `} `; export default Transactions;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/Balance.tsx
import styled, { css } from "styled-components"; import { PgTheme } from "../../utils/pg"; import { useBalance } from "../../hooks"; const Balance = () => { const { balance } = useBalance(); if (balance === null) return null; return <Wrapper>{balance === 0 ? 0 : balance.toFixed(3)} SOL</Wrapper>; }; const Wrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.wallet.main.balance)}; `} `; export default Balance;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/index.ts
export { default } from "./Wallet";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/Send.tsx
import { useEffect, useState } from "react"; import styled, { css } from "styled-components"; import Button from "../Button"; import Input from "../Input"; import Foldable from "../Foldable"; import { PgCommon, PgTerminal, PgTheme, PgTx, PgWallet, PgWeb3, } from "../../utils/pg"; import { useBalance, useKeybind } from "../../hooks"; const Send = () => ( <Wrapper> <Foldable element={<Title>Send</Title>}> <SendExpanded /> </Foldable> </Wrapper> ); const Wrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.wallet.main.send.default)}; `} `; const Title = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.wallet.main.send.title)}; `} `; const SendExpanded = () => { const [recipient, setRecipient] = useState(""); const [amount, setAmount] = useState(""); const [disabled, setDisabled] = useState(true); const { balance } = useBalance(); // Send button disable useEffect(() => { setDisabled( !( PgCommon.isPk(recipient) && PgCommon.isFloat(amount) && balance && balance > parseFloat(amount) ) ); }, [recipient, amount, balance]); const send = async () => { if (disabled) return; await PgTerminal.process(async () => { PgTerminal.log( PgTerminal.info(`Sending ${amount} SOL to ${recipient}...`) ); let msg; try { const ix = PgWeb3.SystemProgram.transfer({ fromPubkey: PgWallet.current!.publicKey, toPubkey: new PgWeb3.PublicKey(recipient), lamports: PgCommon.solToLamports(parseFloat(amount)), }); const tx = new PgWeb3.Transaction().add(ix); const txHash = await PgTx.send(tx); PgTx.notify(txHash); const txResult = await PgCommon.transition(PgTx.confirm(txHash)); if (txResult?.err) throw txResult.err; msg = PgTerminal.success("Success."); // Reset inputs setRecipient(""); setAmount(""); } catch (e: any) { const convertedError = PgTerminal.convertErrorMessage(e.message); msg = `Transfer error: ${convertedError}`; } finally { PgTerminal.log(msg + "\n"); } }); }; useKeybind("Enter", send); return ( <ExpandedWrapper> <ExpandedInput value={recipient} onChange={(ev) => setRecipient(ev.target.value)} validator={PgCommon.isPk} placeholder="Recipient address" /> <ExpandedInput value={amount} onChange={(ev) => setAmount(ev.target.value)} validator={(input) => { if ( !PgCommon.isFloat(input) || (balance && parseFloat(input) > balance) ) { throw new Error("Invalid amount"); } }} placeholder="SOL amount" /> <ExpandedButton onClick={send} btnLoading={{ text: "Sending..." }} disabled={disabled} kind="primary-transparent" fullWidth > Send </ExpandedButton> </ExpandedWrapper> ); }; const ExpandedWrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.wallet.main.send.expanded.default)}; `} `; const ExpandedInput = styled(Input)` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.wallet.main.send.expanded.input)}; `} `; const ExpandedButton = styled(Button)` ${({ theme }) => css` ${PgTheme.convertToCSS( theme.components.wallet.main.send.expanded.sendButton )}; `} `; export default Send;
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/Modals/Approve.tsx
import { FC } from "react"; import styled from "styled-components"; import Modal from "../../Modal"; interface ApproveProps {} // TODO: const Approve: FC<ApproveProps> = ({}) => { const handleApprove = () => {}; return ( <Modal title buttonProps={{ text: "Approve", onSubmit: handleApprove }}> <Content>Approve tx</Content> </Modal> ); }; const Content = styled.div``; export default Approve;
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/Modals/Add.tsx
import { useState } from "react"; import styled, { css } from "styled-components"; import Button from "../../Button"; import Input from "../../Input"; import Modal from "../../Modal"; import Text from "../../Text"; import { Info } from "../../Icons"; import { PgWallet, PgWeb3 } from "../../../utils/pg"; export const Add = () => { const [keypair] = useState(PgWeb3.Keypair.generate); const [name, setName] = useState(PgWallet.getNextAvailableAccountName); const [error, setError] = useState<string | null>(null); const handleCreate = () => PgWallet.add({ name, keypair }); const handleExport = () => PgWallet.export(keypair); return ( <Modal title buttonProps={{ text: "Create", onSubmit: handleCreate, }} error={error} setError={setError} > <MainContent> <MainText>Are you sure you want to create a new wallet?</MainText> <Desc>This will create a brand new keypair.</Desc> <InputWrapper> <InputLabel>Account name</InputLabel> <Input value={name} onChange={(ev) => setName(ev.target.value)} validator={PgWallet.validateAccountName} error={error} setError={setError} /> </InputWrapper> <WarningTextWrapper> <Text icon={<Info color="info" />}> Saving the keypair will allow you to recover the wallet. </Text> </WarningTextWrapper> <Button onClick={handleExport}>Save keypair</Button> </MainContent> </Modal> ); }; const MainContent = styled.div` display: flex; flex-direction: column; padding: 0 1rem; & > a { margin-top: 1rem; } & > button { margin-top: 0.5rem; width: fit-content; } `; const MainText = styled.span` font-weight: bold; `; const Desc = styled.span` ${({ theme }) => css` font-size: ${theme.font.code.size.small}; color: ${theme.colors.default.textSecondary}; margin-top: 0.5rem; `} `; const WarningTextWrapper = styled.div` margin-top: 1rem; display: flex; align-items: center; & svg { height: 2rem; width: 2rem; margin-right: 1rem; } `; const InputWrapper = styled.div` margin-top: 0.75rem; `; const InputLabel = styled.div` margin-bottom: 0.25rem; font-weight: bold; `;
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/Modals/Remove.tsx
import styled, { css } from "styled-components"; import Button from "../../Button"; import Modal from "../../Modal"; import Text from "../../Text"; import { Warning } from "../../Icons"; import { PgWallet } from "../../../utils/pg"; export const Remove = () => { const handleRemove = () => PgWallet.remove(); const handleExport = () => PgWallet.export(); return ( <Modal title buttonProps={{ text: "Remove", kind: "error", onSubmit: handleRemove, }} > <MainContent> <MainText>Are you sure you want to remove the current wallet?</MainText> <Desc>This action is irreversable!</Desc> <WarningTextWrapper> <Text icon={<Warning color="warning" />}> You can recover the wallet later if you save the keypair. </Text> </WarningTextWrapper> <Button onClick={handleExport}>Save keypair</Button> </MainContent> </Modal> ); }; const MainContent = styled.div` display: flex; flex-direction: column; padding: 0 1rem; & > a { margin-top: 1rem; } & > button { margin-top: 1rem; width: fit-content; } `; const MainText = styled.span` font-weight: bold; `; const Desc = styled.span` ${({ theme }) => css` font-size: ${theme.font.code.size.small}; color: ${theme.colors.default.textSecondary}; margin-top: 0.5rem; `} `; const WarningTextWrapper = styled.div` margin-top: 1rem; display: flex; align-items: center; & svg { height: 2rem; width: 2rem; margin-right: 1rem; } `;
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/Modals/Setup.tsx
import { useState } from "react"; import styled, { css } from "styled-components"; import Button from "../../Button"; import Modal from "../../Modal"; import Text from "../../Text"; import { Warning } from "../../Icons"; import { PgWallet, PgWeb3 } from "../../../utils/pg"; export const Setup = () => { const [text, setText] = useState(""); const [keypair] = useState(PgWeb3.Keypair.generate); const handleSetup = () => { if (!PgWallet.accounts.length) PgWallet.add({ keypair }); return true; }; const handleExport = () => { if (!PgWallet.accounts.length) PgWallet.export(keypair); else PgWallet.export(); }; const handleImport = async () => { try { if (PgWallet.accounts.length) PgWallet.remove(0); const keypair = await PgWallet.import(); if (keypair) setText("Imported address: " + keypair.publicKey.toBase58()); } catch (err: any) { console.log(err.message); } }; return ( <Modal title="Playground Wallet" buttonProps={{ text: "Continue", onSubmit: handleSetup, }} > <Content> <ContentTitle>What is it?</ContentTitle> <ContentText> Playground wallet is a native wallet that speeds up development by auto-approving transactions. </ContentText> </Content> <Content> <ContentTitle>How to setup?</ContentTitle> <ContentText> You don't need to do anything other than saving the keypair for future use. You can also choose to import an existing wallet. </ContentText> <WarningTextWrapper> <Text kind="warning" icon={<Warning color="warning" />}> Wallet information is stored in your browser's local storage. You are going to lose the wallet if you clear your browser history unless you save the keypair. </Text> </WarningTextWrapper> <WalletButtonsWrapper> <Button onClick={handleExport} kind="primary-outline"> Save keypair </Button> <Button onClick={handleImport}>Import keypair</Button> </WalletButtonsWrapper> {text && <KeypairText>{text}</KeypairText>} </Content> </Modal> ); }; const Content = styled.div` padding: 0 1rem; &:not(:first-child) { margin-top: 1rem; } `; const ContentTitle = styled.div` margin-bottom: 0.25rem; font-weight: bold; `; const ContentText = styled.p` color: ${({ theme }) => theme.colors.default.textSecondary}; `; const WarningTextWrapper = styled.div` margin-top: 1rem; display: flex; align-items: center; & div > svg { height: 2rem; width: 2rem; margin-right: 1rem; } `; const WalletButtonsWrapper = styled.div` margin-top: 1rem; display: flex; & button { margin-right: 1rem; } `; const KeypairText = styled.div` ${({ theme }) => css` margin-top: 1rem; font-size: ${theme.font.code.size.small}; color: ${theme.colors.default.textSecondary}; `} `;
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/hooks/useStandardAccountChange.tsx
import { useEffect } from "react"; import { useWallet } from "../../../hooks"; import { PgWallet } from "../../../utils/pg"; /** * Update the standard wallet when the user switches between accounts. * * This only applies to Standard Wallets. */ export const useStandardAccountChange = () => { const { wallet } = useWallet(); useEffect(() => { if (!wallet || wallet.isPg) return; // Derive the standard wallet const handleStandardAccountChange = () => { PgWallet.update({ standardName: PgWallet.standardName }); }; wallet.on("connect", handleStandardAccountChange); return () => { wallet.off("connect", handleStandardAccountChange); }; }, [wallet]); };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/hooks/useSyncBalance.tsx
import { useEffect } from "react"; import { useConnection, useWallet } from "../../../hooks"; import { PgCommon, PgConnection, PgWallet } from "../../../utils/pg"; /** Sync the balance of the current wallet. */ export const useSyncBalance = () => { const { connection, isConnected } = useConnection(); const { wallet } = useWallet(); useEffect(() => { if (!PgConnection.isReady(connection) || !wallet) { PgWallet.balance = null; return; } // Listen for balance changes const id = connection.onAccountChange(wallet.publicKey, (acc) => { PgWallet.balance = PgCommon.lamportsToSol(acc.lamports); }); const fetchBalance = async () => { try { const lamports = await connection.getBalance(wallet.publicKey); PgWallet.balance = PgCommon.lamportsToSol(lamports); } catch (e: any) { console.log("Couldn't fetch balance:", e.message); PgWallet.balance = null; } }; fetchBalance(); return () => { connection.removeAccountChangeListener(id); }; }, [wallet, connection, isConnected]); };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/hooks/useDarken.tsx
import { useCallback } from "react"; import { ClassName, Id } from "../../../constants"; /** Darken/lighten the wallet component. */ export const useDarken = () => { const darken = useCallback(() => { document.getElementById(Id.WALLET_MAIN)?.classList.add(ClassName.DARKEN); }, []); const lighten = useCallback(() => { document.getElementById(Id.WALLET_MAIN)?.classList.remove(ClassName.DARKEN); }, []); return { darken, lighten }; };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/hooks/useAirdrop.tsx
import { useEffect, useState } from "react"; import { Emoji } from "../../../constants"; import { PgCommon, PgConnection, PgTerminal, PgTx, PgWallet, } from "../../../utils/pg"; export const useAirdrop = () => { const [airdropAmount, setAirdropAmount] = useState<ReturnType<typeof PgCommon["getAirdropAmount"]>>(null); useEffect(() => { const { dispose } = PgConnection.onDidChangeCurrent((connection) => { setAirdropAmount(PgCommon.getAirdropAmount(connection.rpcEndpoint)); }); return dispose; }, []); const airdrop = async () => { await PgTerminal.process(async () => { if (!airdropAmount) return; let msg; try { PgTerminal.log(PgTerminal.info("Sending an airdrop request...")); const conn = PgConnection.current; const walletPk = PgWallet.current!.publicKey; // Airdrop tx is sometimes successful even when the balance hasn't // changed. To solve this, we check before and after balance instead // of confirming the tx. const beforeBalance = await conn.getBalance(walletPk, "processed"); const txHash = await conn.requestAirdrop( walletPk, PgCommon.solToLamports(airdropAmount) ); PgTx.notify(txHash); // Allow enough time for balance to update by waiting for confirmation await PgTx.confirm(txHash, conn); const afterBalance = await conn.getBalance(walletPk, "processed"); if (afterBalance > beforeBalance) { msg = `${Emoji.CHECKMARK} ${PgTerminal.success( "Success." )} Received ${PgTerminal.bold(airdropAmount.toString())} SOL.`; } else { msg = `${Emoji.CROSS} ${PgTerminal.error( "Error receiving airdrop." )}`; } } catch (e: any) { const convertedError = PgTerminal.convertErrorMessage(e.message); msg = `${Emoji.CROSS} ${PgTerminal.error( "Error receiving airdrop:" )}: ${convertedError}`; } finally { PgTerminal.log(msg + "\n"); } }); }; return { airdrop, airdropCondition: !!airdropAmount }; };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/hooks/index.ts
export { useAirdrop } from "./useAirdrop"; export { useAutoAirdrop } from "./useAutoAirdrop"; export { useDarken } from "./useDarken"; export { useStandardAccountChange } from "./useStandardAccountChange"; export { useSyncBalance } from "./useSyncBalance";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet
solana_public_repos/solana-playground/solana-playground/client/src/components/Wallet/hooks/useAutoAirdrop.tsx
import { useEffect, useRef } from "react"; import { PgCommon, PgConnection, PgSettings, PgTx } from "../../../utils/pg"; import { useBalance, useConnection, useRenderOnChange, useWallet, } from "../../../hooks"; /** Request airdrop when necessary. */ export const useAutoAirdrop = () => { const automaticAirdrop = useRenderOnChange( PgSettings.onDidChangeWalletAutomaticAirdrop ); const { connection } = useConnection(); const { wallet } = useWallet(); // Auto airdrop if balance is less than 4 SOL const airdropping = useRef(false); const { balance } = useBalance(); useEffect(() => { const airdrop = async (_balance = balance, airdropError = false) => { if ( !automaticAirdrop || !PgConnection.isReady(connection) || !wallet || airdropping.current || airdropError || _balance === null || _balance >= 5 ) { return; } // Get cap amount for airdrop based on network const airdropAmount = PgCommon.getAirdropAmount(connection.rpcEndpoint); if (!airdropAmount) return; try { airdropping.current = true; const txHash = await connection.requestAirdrop( wallet.publicKey, PgCommon.solToLamports(airdropAmount) ); await PgTx.confirm(txHash, { connection: connection, commitment: "finalized", }); } catch (e: any) { console.log(e.message); airdropError = true; } finally { airdropping.current = false; _balance = PgCommon.lamportsToSol( await connection.getBalance(wallet.publicKey) ); airdrop(_balance, airdropError); } }; airdrop(); }, [automaticAirdrop, wallet, connection, balance]); };
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Resizable/Resizable.tsx
import { forwardRef } from "react"; import styled, { css } from "styled-components"; import { Resizable as ReResizable, ResizableProps as ReResizableProps, Enable, } from "re-resizable"; type ResizableProps = Omit<ReResizableProps, "enable"> & { enable?: Enable | "top" | "right" | "bottom" | "left"; }; const Resizable = forwardRef<ReResizable, ResizableProps>((props, ref) => ( <StyledResizable ref={ref} {...{ ...props, enable: transformEnable(props.enable), onResizeStart: (ev, dir, ref) => { // Having a transition makes resizing experience laggy. To solve, we // disable the transition when resizing starts, and re-enable it // after resizing stops. ref.style.transitionDuration = "0s"; props.onResizeStart?.(ev, dir, ref); }, onResizeStop: (ev, dir, ref, delta) => { // Setting to empty string restores the default value ref.style.transitionDuration = ""; props.onResizeStop?.(ev, dir, ref, delta); }, }} /> )); const StyledResizable = styled(ReResizable)` ${({ theme }) => css` transition: height, width; transition-duration: ${theme.default.transition.duration.long}; transition-timing-function: ${theme.default.transition.type}; `} `; const transformEnable = ( enable: ResizableProps["enable"] ): ReResizableProps["enable"] => { if (!enable || typeof enable === "object") return enable; const KEYS: Array<keyof Enable> = [ "bottom", "bottomLeft", "bottomRight", "left", "right", "top", "topLeft", "topRight", ]; const ALL_FALSE = Object.values(KEYS).reduce((acc, cur) => { acc[cur] = false; return acc; }, {} as Enable); switch (enable) { case "bottom": return { ...ALL_FALSE, bottom: true }; case "left": return { ...ALL_FALSE, left: true }; case "right": return { ...ALL_FALSE, right: true }; case "top": return { ...ALL_FALSE, top: true }; } }; export default Resizable;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Resizable/index.ts
export { default } from "./Resizable";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Text/index.ts
export { default } from "./Text"; export type { TextKind } from "./Text";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Text/Text.tsx
import { ComponentPropsWithoutRef, forwardRef, ReactNode } from "react"; import styled, { css } from "styled-components"; import { useDifferentBackground } from "../../hooks"; import { PgTheme } from "../../utils/pg"; export type TextKind = "default" | "info" | "warning" | "success" | "error"; interface TextProps extends ComponentPropsWithoutRef<"div"> { kind?: TextKind; icon?: ReactNode; } /** A text component that always have a different background than its parent */ const Text = forwardRef<HTMLDivElement, TextProps>( ({ icon, children, ...props }, refProp) => { const { ref } = useDifferentBackground(); return ( <Wrapper ref={refProp ?? ref} icon={icon} {...props}> {icon && <IconWrapper>{icon}</IconWrapper>} <ContentWrapper>{children}</ContentWrapper> </Wrapper> ); } ); const Wrapper = styled.div<TextProps>` ${({ kind, icon, theme }) => { kind ??= "default"; // Clone the default Text theme to not override the global object let text = structuredClone(theme.components.text.default); switch (kind) { case "info": case "warning": case "success": case "error": text.color = theme.colors.state[kind].color; } // Text kind specific overrides // NOTE: Overrides must come after setting the `TextProps` defaults text = PgTheme.overrideDefaults( text, theme.components.text.overrides?.[kind] ); return css` ${PgTheme.convertToCSS(text)}; ${!!icon && `& div > svg { width: 1.5rem; height: 1.5rem; margin-right: 0.75rem; }`} `; }} `; const IconWrapper = styled.div` display: flex; justify-content: center; align-items: center; `; const ContentWrapper = styled.div` & > p:not(:first-child) { margin-top: 1rem; } `; export default Text;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Select/index.ts
export { default } from "./Select";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Select/Select.tsx
import ReactSelect, { GroupBase, Props } from "react-select"; import styled, { css, useTheme } from "styled-components"; import { PgTheme } from "../../utils/pg"; const Select = < Option, IsMulti extends boolean = false, Group extends GroupBase<Option> = GroupBase<Option> >( props: Props<Option, IsMulti, Group> ) => { const theme = useTheme(); const select = theme.components.select; return ( // @ts-ignore <StyledReactSelect styles={{ control: (base) => ({ ...base, ...mapTheme(select.control), ":hover": mapTheme(select.control.hover), ":focus-within": mapTheme(select.control.focusWithin), }), menu: (base) => ({ ...base, ...mapTheme(select.menu), }), option: (base, state) => { const stateStyle = state.isFocused ? mapTheme(select.option.focus) : {}; return { ...base, display: "flex", alignItems: "center", ...mapTheme(select.option), ...stateStyle, "::before": { content: `"${state.isSelected ? "✔" : ""}"`, width: "0.5rem", height: "0.5rem", display: "flex", alignItems: "center", marginRight: "0.5rem", ...mapTheme(select.option.before), }, ":active": mapTheme(select.option.active), }; }, singleValue: (base) => ({ ...base, ...mapTheme(select.singleValue), }), input: (base) => ({ ...base, ...mapTheme(select.input) }), groupHeading: (base) => ({ ...base, ...mapTheme(select.groupHeading), }), dropdownIndicator: (base) => ({ ...base, ...mapTheme(select.dropdownIndicator), "> svg": { color: select.dropdownIndicator.color, height: "1rem", width: "1rem", }, }), indicatorSeparator: (base) => ({ ...base, ...mapTheme(select.indicatorSeparator), }), }} {...props} /> ); }; const StyledReactSelect = styled(ReactSelect)` ${({ theme }) => css` ${PgTheme.getScrollbarCSS({ allChildren: true, width: "0.25rem", height: "0.25rem", })}; ${PgTheme.convertToCSS(theme.components.select.default)}; `} `; const mapTheme = (theme: any) => ({ ...theme, background: theme.bg }); export default Select;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/FilePicker/FilePicker.tsx
import { ChangeEvent, Dispatch, FC, SetStateAction, useCallback, useEffect, useMemo, useRef, } from "react"; import styled, { css } from "styled-components"; import Checkbox from "../Checkbox"; import LangIcon from "../LangIcon"; import { PgCommon, PgExplorer } from "../../utils/pg"; import { useDifferentBackground } from "../../hooks"; interface FilePickerProps { path: string; filePaths: string[]; setFilePaths: Dispatch<SetStateAction<string[]>>; } const FilePicker: FC<FilePickerProps> = ({ path, filePaths, setFilePaths }) => { const { ref } = useDifferentBackground(); // Handle checkbox `checked` useEffect(() => { const checkboxes = ref.current!.getElementsByTagName("input"); for (const checkbox of checkboxes) { const dataPath = PgExplorer.getItemPathFromEl(checkbox); if (!dataPath) continue; const checked = filePaths.some((path) => path.startsWith(dataPath)); checkbox.checked = checked; } }, [filePaths, ref]); return ( <Wrapper ref={ref}> <RecursiveFolder path={path} setFilePaths={setFilePaths} /> </Wrapper> ); }; const Wrapper = styled.div` padding: 0.5rem 0; border-radius: ${({ theme }) => theme.default.borderRadius}; `; type RecursiveFolderProps = Omit<FilePickerProps, "filePaths">; const RecursiveFolder: FC<RecursiveFolderProps> = ({ path, setFilePaths }) => { const folderName = useMemo( () => PgExplorer.getItemNameFromPath(path), [path] ); const depth = useMemo( () => PgExplorer.getRelativePath(path).split("/").length - 1, [path] ); const { files, folders } = useMemo( () => PgExplorer.getFolderContent(path), [path] ); const toggleCheck = useCallback( (ev: ChangeEvent<HTMLInputElement>) => { const paths: string[] = []; const startEl = PgExplorer.getItemTypeFromEl(ev.target)?.file ? ev.target.parentElement!.parentElement! : wrapperRef.current!; const recursivelyGetPaths = (el: Element) => { for (const childEl of el.children) { if (childEl.getAttribute("type") === "checkbox") { const path = PgExplorer.getItemPathFromEl(childEl); if (path) paths.push(path); } else { recursivelyGetPaths(childEl); } } }; recursivelyGetPaths(startEl); setFilePaths((previousPaths) => { const filePaths = paths.filter( (path) => PgExplorer.getItemTypeFromPath(path).file ); if (ev.target.checked) return [...previousPaths, ...filePaths]; return previousPaths.filter((path) => !filePaths.includes(path)); }); }, [setFilePaths] ); const wrapperRef = useRef<HTMLDivElement>(null); return ( <Folder ref={wrapperRef}> <FolderName> <StyledCheckbox depth={depth} label={folderName} onChange={toggleCheck} defaultChecked data-path={path} /> </FolderName> {folders .sort((a, b) => { // Prioritize `src` dir if (b === PgExplorer.PATHS.SRC_DIRNAME) return 1; return a.localeCompare(b); }) .map((name) => ( <RecursiveFolder key={name} path={PgCommon.joinPaths(path, name, "/")} setFilePaths={setFilePaths} /> ))} {files .sort((a, b) => a.localeCompare(b)) .map((name) => ( <File key={name}> <StyledCheckbox depth={depth + 1} label={ <FileNameWrapper> <LangIcon path={name} /> <FileName>{name}</FileName> </FileNameWrapper> } onChange={toggleCheck} defaultChecked data-path={PgCommon.joinPaths(path, name)} /> </File> ))} </Folder> ); }; const Folder = styled.div` ${({ theme }) => css` & label { width: 100%; transition: all ${theme.default.transition.duration.short} ${theme.default.transition.type}; &:hover { background: ${theme.colors.state.hover.bg}; } } `} `; const FolderName = styled.div` display: flex; `; const File = styled.div` display: flex; align-items: center; `; const FileNameWrapper = styled.div` display: flex; align-items: center; `; const FileName = styled.span` margin-left: 0.25rem; `; const StyledCheckbox = styled(Checkbox)<{ depth: number }>` margin-left: ${({ depth }) => depth + 1}rem; padding: 0.375rem 0.5rem; height: 2rem; `; export default FilePicker;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/FilePicker/index.ts
export { default } from "./FilePicker";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Modal/index.ts
export { default } from "./Modal";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Modal/Modal.tsx
import { Dispatch, FC, SetStateAction, useCallback, useRef, useState, } from "react"; import styled, { css } from "styled-components"; import Button, { ButtonProps } from "../Button"; import FadeIn from "../FadeIn"; import Text from "../Text"; import { Close, Sad } from "../Icons"; import { PROJECT_NAME } from "../../constants"; import { OrString, PgTheme, PgView, SyncOrAsync } from "../../utils/pg"; import { useKeybind, useOnClickOutside } from "../../hooks"; interface ModalProps { /** Modal title to show. If true, default is "Solana Playground" */ title?: boolean | string; /** Modal's submit button props */ buttonProps?: ButtonProps & { /** Button text to show */ text: OrString<"Continue">; /** Callback function to run on submit */ onSubmit?: () => SyncOrAsync; /** Whether to skip closing the modal when user submits */ noCloseOnSubmit?: boolean; /** Set loading state of the button based on `onSubmit` */ setLoading?: Dispatch<SetStateAction<boolean>>; }; /** Error to display */ error?: any; /** Set the error when `onSubmit` throws */ setError?: Dispatch<SetStateAction<any>>; /** * Whether to show a close button on top-right. * * Defaults to `!buttonProps?.onSubmit`. */ closeButton?: boolean; } const Modal: FC<ModalProps> = ({ title, buttonProps, closeButton = !buttonProps?.onSubmit, children, ...props }) => { const [error, setError] = useState(""); const handleSubmit = useCallback(async () => { if (!buttonProps || buttonProps.disabled) return; try { // Get result const data = await buttonProps.onSubmit?.(); // Close unless explicitly forbidden if (!buttonProps.noCloseOnSubmit) PgView.closeModal(data); } catch (e: any) { if (props.setError) props.setError(e.message); else { setError(e.message); throw e; } } }, [buttonProps, props]); // Submit on Enter // Intentionally clicking the button in order to trigger the button's loading // state on Enter as opposed to using `handleSubmit` which wouldn't change // submit button's state. const buttonRef = useRef<HTMLButtonElement>(null); useKeybind("Enter", () => buttonRef.current?.click()); const wrapperRef = useRef<HTMLDivElement>(null); useOnClickOutside(wrapperRef, PgView.closeModal); return ( <Wrapper ref={wrapperRef}> {/* Take away the focus of other buttons when the modal is mounted */} <FocusButton autoFocus /> <TopWrapper> {title && <Title>{title === true ? PROJECT_NAME : title}</Title>} {closeButton && ( <CloseButtonWrapper hasTitle={!!title}> <Button kind="icon" onClick={PgView.closeModal}> <Close /> </Button> </CloseButtonWrapper> )} </TopWrapper> <ScrollableWrapper> <ContentWrapper> {error && ( <ErrorText kind="error" icon={<Sad />}> {error} </ErrorText> )} {children} </ContentWrapper> {buttonProps && ( <ButtonsWrapper> {!closeButton && buttonProps.onSubmit && ( <Button onClick={PgView.closeModal} kind="transparent"> Cancel </Button> )} <Button {...buttonProps} ref={buttonRef} onClick={handleSubmit} disabled={buttonProps.disabled || !!props.error} size={buttonProps.size} kind={ buttonProps.onSubmit ? buttonProps.kind ?? "primary-transparent" : "outline" } > {buttonProps.text} </Button> </ButtonsWrapper> )} </ScrollableWrapper> </Wrapper> ); }; const Wrapper = styled(FadeIn)` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.modal.default)}; `} `; const TopWrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.modal.top)}; `} `; const Title = styled.div` ${({ theme }) => css` width: 100%; text-align: center; padding: 0.75rem 0; border-bottom: 1px solid ${theme.colors.default.border}; `} `; const CloseButtonWrapper = styled.div<{ hasTitle: boolean }>` ${({ hasTitle }) => hasTitle ? css` position: absolute; top: 0; right: 1.5rem; bottom: 0; margin: auto; display: flex; align-items: center; ` : css` width: 100%; display: flex; justify-content: flex-end; margin-top: 0.5rem; `} `; const ScrollableWrapper = styled.div` overflow-y: auto; overflow-x: hidden; ${PgTheme.getScrollbarCSS()}; `; const ContentWrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.modal.content)}; `} `; const ErrorText = styled(Text)` margin-bottom: 1rem; `; const ButtonsWrapper = styled.div` ${({ theme }) => css` & button:nth-child(2) { margin-left: 1rem; } ${PgTheme.convertToCSS(theme.components.modal.bottom)}; `} `; const FocusButton = styled.button` opacity: 0; position: absolute; `; export default Modal;
0