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/views/sidebar/test/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/Account/Account.tsx
|
import { FC, useState } from "react";
import styled from "styled-components";
import CodeResult from "../CodeResult";
import InputLabel from "../InputLabel";
import Interaction from "../Interaction";
import Button from "../../../../../components/Button";
import Foldable from "../../../../../components/Foldable";
import SearchBar from "../../../../../components/SearchBar";
import Text from "../../../../../components/Text";
import { SpinnerWithBg } from "../../../../../components/Loading";
import { PgCommon, PgWeb3 } from "../../../../../utils/pg";
import { PgProgramInteraction } from "../../../../../utils/pg/program-interaction";
import { useWallet } from "../../../../../hooks";
interface AccountProps {
accountName: string;
index: number;
}
const Account: FC<AccountProps> = ({ accountName, index }) => {
const [enteredAddress, setEnteredAddress] = useState("");
const [enteredAddressError, setEnteredAddressError] = useState(false);
const [fetchedData, setFetchedData] = useState<object>();
const [fetchError, setFetchError] = useState<string | null>(null);
const [fetchOneLoading, setFetchOneLoading] = useState(false);
const [fetchAllLoading, setFetchAllLoading] = useState(false);
const [resultOpen, setResultOpen] = useState(false);
const { wallet } = useWallet();
const handleFetched = (data: object) => {
setFetchedData(data);
setFetchError(null);
setResultOpen(true);
};
const handleError = (e: any) => {
if (e.message.startsWith("Account does not exist")) {
setFetchError("Account does not exist");
} else if (e.message === "Invalid account discriminator") {
setFetchError(`Given account is not type ${accountName}`);
} else {
console.log(e);
setFetchError(`Unknown error: ${e.message}`);
}
setResultOpen(true);
};
const fetchOne = async () => {
setFetchOneLoading(true);
try {
const account = await PgCommon.transition(
PgProgramInteraction.fetchAccount(
accountName,
new PgWeb3.PublicKey(enteredAddress)
)
);
handleFetched(account);
} catch (err: any) {
handleError(err);
} finally {
setFetchOneLoading(false);
}
};
const fetchAll = async () => {
setFetchAllLoading(true);
try {
const allAccounts = await PgCommon.transition(
PgProgramInteraction.fetchAllAccounts(accountName)
);
handleFetched(allAccounts);
} catch (err: any) {
handleError(err);
} finally {
setFetchAllLoading(false);
}
};
return (
<Interaction name={accountName} index={index}>
<InputWrapper>
<InputLabel name="address" type="publicKey" />
<SearchBar
value={enteredAddress}
onChange={(ev) => setEnteredAddress(ev.target.value)}
error={enteredAddressError}
setError={setEnteredAddressError}
validator={PgCommon.isPk}
/>
</InputWrapper>
<ButtonsWrapper>
<Button
onClick={fetchOne}
disabled={!wallet || !enteredAddress || enteredAddressError}
>
Fetch
</Button>
<Button onClick={fetchAll} disabled={!wallet}>
Fetch All
</Button>
</ButtonsWrapper>
{(fetchedData || fetchError) && (
<ResultWrapper>
<Foldable
element={<span>Result</span>}
isOpen={resultOpen}
setIsOpen={setResultOpen}
>
<SpinnerWithBg loading={fetchOneLoading || fetchAllLoading}>
{fetchError ? (
<FetchError kind="error">{fetchError}</FetchError>
) : (
<CodeResult index={index}>
{PgCommon.prettyJSON(fetchedData!)}
</CodeResult>
)}
</SpinnerWithBg>
</Foldable>
</ResultWrapper>
)}
</Interaction>
);
};
const InputWrapper = styled.div`
margin: 0.5rem 0;
`;
const ButtonsWrapper = styled.div`
display: flex;
flex-direction: row;
gap: 0.75rem;
`;
const ResultWrapper = styled.div`
margin-top: 1rem;
width: 100%;
`;
const FetchError = styled(Text)`
width: 100%;
`;
export default Account;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/Account/index.ts
|
export { default } from "./Account";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/Event/Event.tsx
|
import { FC, useEffect, useState } from "react";
import CodeResult from "../CodeResult";
import Interaction from "../Interaction";
import { PgCommon } from "../../../../../utils/pg";
import { PgProgramInteraction } from "../../../../../utils/pg/program-interaction";
import { useConnection, useWallet } from "../../../../../hooks";
import { useIdl } from "../IdlProvider";
interface EventProps {
eventName: string;
index: number;
}
const Event: FC<EventProps> = ({ index, eventName }) => {
const { connection } = useConnection();
const { wallet } = useWallet();
const { idl } = useIdl();
const [receivedEvents, setReceivedEvents] = useState<object[]>([]);
useEffect(() => {
if (!(idl && connection && wallet)) return;
const program = PgProgramInteraction.getAnchorProgram();
const listener = program.addEventListener(eventName, (emittedEvent) => {
setReceivedEvents((eventsSoFar) => [...eventsSoFar, emittedEvent]);
});
return () => {
program.removeEventListener(listener);
};
}, [eventName, idl, connection, wallet]);
return (
<Interaction name={`${eventName} (${receivedEvents.length})`} index={index}>
<CodeResult index={index}>
{receivedEvents.map((ev) => PgCommon.prettyJSON(ev)).join("\n")}
</CodeResult>
</Interaction>
);
};
export default Event;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/Event/index.ts
|
export { default } from "./Event";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/explorer.ts
|
import { createSidebarPage } from "../create";
export const explorer = createSidebarPage({
name: "Explorer",
icon: "explorer.png",
keybind: "Ctrl+Shift+E",
});
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/index.ts
|
export { explorer } from "./explorer";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Workspaces.tsx
|
import { useMemo } from "react";
import styled from "styled-components";
import Button from "../../../../components/Button";
import Select from "../../../../components/Select";
import Text from "../../../../components/Text";
import {
NewWorkspace,
RenameWorkspace,
DeleteWorkspace,
ImportGithub,
ImportFs,
ImportTemporary,
ExportWorkspace,
} from "./Modals";
import {
Edit,
ExportFile,
Github,
ImportFile,
ImportWorkspace,
Info,
Plus,
Trash,
} from "../../../../components/Icons";
import { PgCommon, PgExplorer, PgTutorial, PgView } from "../../../../utils/pg";
import { useExplorer } from "../../../../hooks";
const Workspaces = () => {
if (PgExplorer.isTemporary) return <TemporaryWarning />;
const handleNew = () => PgView.setModal(NewWorkspace);
const handleRename = () => PgView.setModal(RenameWorkspace);
const handleDelete = () => PgView.setModal(DeleteWorkspace);
const handleGithub = () => PgView.setModal(ImportGithub);
const handleFsImport = () => PgView.setModal(ImportFs);
const handleFsExport = () => PgView.setModal(ExportWorkspace);
return (
<Wrapper>
<TopWrapper>
<MainText>Projects</MainText>
<ButtonsWrapper>
<Button onClick={handleNew} kind="icon" title="Create">
<Plus />
</Button>
<Button onClick={handleRename} kind="icon" title="Rename">
<Edit />
</Button>
<Button
onClick={handleDelete}
kind="icon"
hoverColor="error"
title="Delete"
>
<Trash />
</Button>
<Button onClick={handleGithub} kind="icon" title="Import from Github">
<Github />
</Button>
<Button
onClick={handleFsImport}
kind="icon"
title="Import from local file system"
>
<ImportFile />
</Button>
<Button onClick={handleFsExport} kind="icon" title="Export">
<ExportFile />
</Button>
</ButtonsWrapper>
</TopWrapper>
<WorkspaceSelect />
</Wrapper>
);
};
const WorkspaceSelect = () => {
const { explorer } = useExplorer();
const options = useMemo(() => {
const [tutorials, projects] = PgCommon.filterWithRemaining(
PgExplorer.allWorkspaceNames!,
PgTutorial.isWorkspaceTutorial
);
const projectOptions = [
{
label: "Projects",
options: projects.map((name) => ({ value: name, label: name })),
},
];
if (!tutorials.length) return projectOptions;
return projectOptions.concat([
{
label: "Tutorials",
options: tutorials.map((name) => ({ value: name, label: name })),
},
]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [explorer.currentWorkspaceName]);
const value = useMemo(() => {
for (const option of options) {
const val = option.options.find(
(option) => option.value === explorer.currentWorkspaceName
);
if (val) return val;
}
}, [explorer.currentWorkspaceName, options]);
return (
<SelectWrapper>
<Select
options={options}
value={value}
onChange={async (props) => {
const name = props?.value!;
if (PgExplorer.currentWorkspaceName === name) return;
if (PgTutorial.isWorkspaceTutorial(name)) await PgTutorial.open(name);
else await PgExplorer.switchWorkspace(name);
}}
/>
</SelectWrapper>
);
};
const Wrapper = styled.div`
margin: 1.5rem 0.5rem 0 0.5rem;
padding: 0 0.5rem;
`;
const TopWrapper = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
`;
const MainText = styled.div`
${({ theme }) => `
color: ${theme.colors.default.textSecondary};
font-size: ${theme.font.code.size.large};
`}
`;
const ButtonsWrapper = styled.div`
margin-left: 0.5rem;
display: flex;
align-items: center;
gap: 0 0.5rem;
`;
const SelectWrapper = styled.div`
& > select {
width: 100%;
}
`;
const TemporaryWarning = () => {
const handleImport = () => PgView.setModal(ImportTemporary);
return (
<TemporaryWarningWrapper>
<Text icon={<Info color="info" />}>
This is a temporary project, import it to persist changes.
</Text>
<Button onClick={handleImport} leftIcon={<ImportWorkspace />} fullWidth>
Import
</Button>
</TemporaryWarningWrapper>
);
};
const TemporaryWarningWrapper = styled.div`
padding: 1rem 0.5rem;
& > button {
margin-top: 0.75rem;
}
`;
export default Workspaces;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/ExplorerContextMenu.tsx
|
import { FC } from "react";
import Menu from "../../../../components/Menu";
import {
Edit,
NewFile,
NewFolder,
Rocket,
RunAll,
TestPaper,
TestTube,
Trash,
Triangle,
Wrench,
} from "../../../../components/Icons";
import { PgExplorer } from "../../../../utils/pg";
import type { useExplorerContextMenu } from "./useExplorerContextMenu";
type ExplorerContextMenuProps = ReturnType<typeof useExplorerContextMenu>;
export const ExplorerContextMenu: FC<ExplorerContextMenuProps> = ({
itemData,
ctxNewItem,
renameItem,
deleteItem,
runBuild,
runDeploy,
runClient,
runClientFolder,
runTest,
runTestFolder,
handleMenu,
children,
}) => {
return (
<Menu.Context
items={[
{
name: "New File",
onClick: ctxNewItem,
keybind: "ALT+N",
icon: <NewFile />,
showCondition: itemData.isFolder,
},
{
name: "New Folder",
onClick: ctxNewItem,
keybind: "ALT+N",
icon: <NewFolder />,
showCondition: itemData.isFolder,
},
{
name: "Rename",
onClick: renameItem,
keybind: "F2",
icon: <Edit />,
},
{
name: "Delete",
onClick: deleteItem,
keybind: "Del",
icon: <Trash />,
hoverColor: "error",
},
{
name: "Build",
onClick: runBuild,
icon: <Wrench />,
showCondition: itemData.isProgramFolder,
},
{
name: "Deploy",
onClick: runDeploy,
icon: <Rocket />,
showCondition: itemData.isProgramFolder,
},
{
name: "Run",
onClick: runClient,
icon: <Triangle rotate="90deg" />,
showCondition: itemData.isClient,
},
{
name: "Run All",
onClick: runClientFolder,
icon: <RunAll />,
showCondition: itemData.isClientFolder,
},
{
name: "Test",
onClick: runTest,
icon: <TestTube />,
showCondition: itemData.isTest,
},
{
name: "Test All",
onClick: runTestFolder,
icon: <TestPaper />,
showCondition: itemData.isTestFolder,
},
]}
onContextMenu={handleMenu}
onHide={PgExplorer.removeCtxSelectedEl}
>
{children}
</Menu.Context>
);
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Explorer.tsx
|
import styled from "styled-components";
import Folders from "./Folders";
import NoWorkspace from "./NoWorkspace";
import Workspaces from "./Workspaces";
import { useExplorer } from "../../../../hooks";
const Explorer = () => {
const { explorer } = useExplorer({ checkInitialization: true });
if (!explorer?.isTemporary) {
if (!explorer?.allWorkspaceNames) return null;
if (explorer.allWorkspaceNames.length === 0) return <NoWorkspace />;
}
return (
<Wrapper>
<Workspaces />
<Folders />
</Wrapper>
);
};
const Wrapper = styled.div`
display: flex;
flex-direction: column;
width: 100%;
user-select: none;
`;
export default Explorer;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Folders.tsx
|
import {
ComponentPropsWithoutRef,
CSSProperties,
FC,
forwardRef,
MouseEvent,
ReactNode,
useCallback,
useMemo,
useState,
} from "react";
import styled, { css, useTheme } from "styled-components";
import ExplorerButtons from "./ExplorerButtons";
import Button, { ButtonProps } from "../../../../components/Button";
import Dnd, { DragStartEvent, DragEndEvent } from "../../../../components/Dnd";
import LangIcon from "../../../../components/LangIcon";
import { ExplorerContextMenu } from "./ExplorerContextMenu";
import { ReplaceItem } from "./Modals";
import {
Plus,
Rocket,
ShortArrow,
TestTube,
Triangle,
Wrench,
} from "../../../../components/Icons";
import { ClassName, Id, ItemError } from "../../../../constants";
import { PgCommon, PgExplorer, PgView } from "../../../../utils/pg";
import { useExplorerContextMenu } from "./useExplorerContextMenu";
import { useHandleItemState } from "./useHandleItemState";
import { useNewItem } from "./useNewItem";
import { useKeybind } from "../../../../hooks";
const Folders = () => {
useHandleItemState();
const ctxMenu = useExplorerContextMenu();
const { newItem } = useNewItem();
useKeybind(
[
{ keybind: "Alt+N", handle: newItem },
{ keybind: "F2", handle: ctxMenu.renameItem },
{ keybind: "Delete", handle: ctxMenu.deleteItem },
],
[]
);
// No need to memoize here
const relativeRootPath = PgExplorer.getProjectRootPath();
const { folders } = PgExplorer.getFolderContent(relativeRootPath);
const otherFolders = folders.filter(
(f) =>
f !== PgExplorer.PATHS.SRC_DIRNAME &&
f !== PgExplorer.PATHS.CLIENT_DIRNAME &&
f !== PgExplorer.PATHS.TESTS_DIRNAME
);
return (
<>
<ExplorerButtons />
<ExplorerDndContext>
<ExplorerContextMenu {...ctxMenu}>
<RootWrapper id={Id.ROOT_DIR} data-path={relativeRootPath}>
{/* Program */}
<SectionTopWrapper>
<SectionHeader>Program</SectionHeader>
{folders.includes(PgExplorer.PATHS.SRC_DIRNAME) ? (
<>
<SectionButton
onClick={ctxMenu.runBuild}
icon={<Wrench />}
addTextMargin
>
Build
</SectionButton>
<SectionButton
onClick={ctxMenu.runDeploy}
icon={<Rocket />}
addTextMargin
disabled={ctxMenu.deployState !== "ready"}
>
Deploy
</SectionButton>
</>
) : (
<SectionButton onClick={ctxMenu.addProgram} icon={<Plus />}>
Add
</SectionButton>
)}
</SectionTopWrapper>
<FolderGroup
folders={folders.filter(
(f) => f === PgExplorer.PATHS.SRC_DIRNAME
)}
relativeRootPath={relativeRootPath}
/>
{/* Client and tests */}
<SectionTopWrapper>
<SectionHeader>Client</SectionHeader>
{folders.includes(PgExplorer.PATHS.CLIENT_DIRNAME) ? (
<SectionButton
onClick={ctxMenu.runClientFolder}
icon={<Triangle rotate="90deg" />}
title="Run All (in client dir)"
addTextMargin
>
Run
</SectionButton>
) : (
<SectionButton onClick={ctxMenu.addClient} icon={<Plus />}>
Add client
</SectionButton>
)}
{folders.includes(PgExplorer.PATHS.TESTS_DIRNAME) ? (
<SectionButton
onClick={ctxMenu.runTestFolder}
icon={<TestTube />}
title="Test All (in tests dir)"
>
Test
</SectionButton>
) : (
<SectionButton onClick={ctxMenu.addTests} icon={<Plus />}>
Add tests
</SectionButton>
)}
</SectionTopWrapper>
<FolderGroup
folders={folders.filter(
(f) =>
f === PgExplorer.PATHS.CLIENT_DIRNAME ||
f === PgExplorer.PATHS.TESTS_DIRNAME
)}
relativeRootPath={relativeRootPath}
/>
{/* Other */}
{otherFolders.length > 0 && (
<SectionTopWrapper>
<SectionHeader>Other</SectionHeader>
</SectionTopWrapper>
)}
<FolderGroup
folders={otherFolders}
relativeRootPath={relativeRootPath}
/>
</RootWrapper>
</ExplorerContextMenu>
</ExplorerDndContext>
</>
);
};
const ExplorerDndContext: FC = ({ children }) => {
const [activeItemProps, setActiveItemProps] = useState<any>(null);
const [parentFolderEl, setParentFolderEl] = useState<HTMLElement | null>(
null
);
const handleDragStart = useCallback((ev: DragStartEvent) => {
const props: any = ev.active.data.current;
const el = PgExplorer.getElFromPath(props.path);
if (!el) return;
// Get the class name from the element to persist the folder open state
setActiveItemProps({ ...props, className: el.className });
setParentFolderEl(el.parentElement!);
}, []);
const handleDragEnd = useCallback(async (ev: DragEndEvent) => {
const { active, over } = ev;
if (!over) return;
const fromPath = active.id as string;
const toPath = over.id as string;
if (PgCommon.isPathsEqual(fromPath, toPath)) return;
// Destination should be a folder
const isToPathFolder = PgExplorer.getItemTypeFromPath(toPath).folder;
if (!isToPathFolder) return;
// Should not be able to move parent dir into child
const isFromPathFolder = PgExplorer.getItemTypeFromPath(fromPath).folder;
if (isFromPathFolder && toPath.startsWith(fromPath)) return;
const itemName = PgExplorer.getItemNameFromPath(fromPath);
const newPath = PgExplorer.getCanonicalPath(
PgCommon.joinPaths(toPath, itemName)
);
if (PgCommon.isPathsEqual(fromPath, newPath)) return;
try {
await PgExplorer.renameItem(fromPath, newPath, {
skipNameValidation: true,
});
} catch (e: any) {
if (e.message === ItemError.ALREADY_EXISTS) {
await PgView.setModal(
<ReplaceItem fromPath={fromPath} toPath={newPath} />
);
}
}
}, []);
const Item = activeItemProps
? PgExplorer.getItemTypeFromPath(activeItemProps.path).file
? StyledFile
: StyledFolder
: null;
return (
<Dnd.Context
dragOverlay={{
Element: Item && <Item {...activeItemProps} />,
portalContainer: parentFolderEl,
dropAnimation: null,
}}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
{children}
</Dnd.Context>
);
};
interface SectionButtonProps extends ButtonProps {
icon: ReactNode;
addTextMargin?: boolean;
}
const SectionButton: FC<SectionButtonProps> = ({
onClick,
icon,
addTextMargin,
children,
...props
}) => (
<Button onClick={onClick} kind="icon" {...props}>
{icon}
<SectionButtonText addTextMargin={addTextMargin}>
{children}
</SectionButtonText>
</Button>
);
const SectionButtonText = styled.span<
Pick<SectionButtonProps, "addTextMargin">
>`
${({ addTextMargin }) => css`
margin: 0 0.25rem;
${addTextMargin && "margin-left: 0.50rem"};
`}
`;
interface FolderGroupProps {
folders: string[];
relativeRootPath: string;
}
const FolderGroup: FC<FolderGroupProps> = ({ folders, relativeRootPath }) => (
<>
{folders
.sort((a, b) => a.localeCompare(b))
.map((folderName) => (
<RecursiveFolder
key={folderName}
path={PgCommon.appendSlash(
PgCommon.joinPaths(relativeRootPath, folderName)
)}
/>
))}
</>
);
interface RecursiveFolderProps {
path: string;
}
const RecursiveFolder: FC<RecursiveFolderProps> = ({ path }) => {
const folderName = useMemo(
() => PgExplorer.getItemNameFromPath(path),
[path]
);
const depth = useMemo(
() => PgExplorer.getRelativePath(path).split("/").length - 2,
[path]
);
// Intentionally don't memoize in order to re-render
const { files, folders } = PgExplorer.getFolderContent(path);
const toggle = useCallback((ev: MouseEvent<HTMLDivElement>) => {
const el = ev.currentTarget;
// Set selected
PgExplorer.setSelectedEl(el);
PgExplorer.setCtxSelectedEl(el);
if (PgExplorer.getItemTypeFromEl(el)?.folder) {
PgExplorer.toggleFolder(el);
} else {
PgExplorer.openFile(PgExplorer.getItemPathFromEl(el)!);
}
}, []);
// Open the folder on drag over
const handleDragOver = useCallback((el) => {
PgExplorer.openFolder(el.firstChild);
}, []);
const theme = useTheme();
const overStyle: CSSProperties = useMemo(
() => ({
background: theme.colors.default.primary + theme.default.transparency.low,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[theme.name]
);
return (
<Dnd.Droppable id={path} onDragOver={handleDragOver} overStyle={overStyle}>
<Dnd.Draggable
id={path}
Item={StyledFolder}
itemProps={{
path,
name: folderName,
depth,
onClick: toggle,
className: ClassName.FOLDER,
}}
/>
<FolderInsideWrapper
className={`${ClassName.FOLDER_INSIDE} ${ClassName.HIDDEN}`}
>
{folders
.sort((a, b) => a.localeCompare(b))
.map((folderName) => (
<RecursiveFolder
key={folderName}
path={PgCommon.appendSlash(PgCommon.joinPaths(path, folderName))}
/>
))}
{files
.sort((a, b) => a.localeCompare(b))
.map((fileName) => (
<Dnd.Draggable
key={fileName}
id={PgCommon.joinPaths(path, fileName)}
Item={StyledFile}
itemProps={{
path: PgCommon.joinPaths(path, fileName),
name: fileName,
depth: depth + 1,
onClick: toggle,
className: ClassName.FILE,
}}
/>
))}
</FolderInsideWrapper>
</Dnd.Droppable>
);
};
interface FileOrFolderProps {
path: string;
name: string;
depth: number;
}
type FolderProps = FileOrFolderProps & ComponentPropsWithoutRef<"div">;
const Folder = forwardRef<HTMLDivElement, FolderProps>(
({ path, name, depth, ...props }, ref) => (
<div ref={ref} data-path={path} {...props}>
<PaddingLeft depth={depth} />
<ShortArrow color="textSecondary" />
<span>{name}</span>
</div>
)
);
type FileProps = FileOrFolderProps & ComponentPropsWithoutRef<"div">;
const File = forwardRef<HTMLDivElement, FileProps>(
({ path, name, depth, ...props }, ref) => (
<div ref={ref} data-path={path} {...props}>
<PaddingLeft depth={depth} />
<LangIcon path={path} />
<span>{name}</span>
</div>
)
);
const RootWrapper = styled.div`
${({ theme }) => css`
padding: 0.375rem 0;
& .${ClassName.FOLDER}, & .${ClassName.FILE} {
display: flex;
align-items: center;
padding: 0.25rem 1rem;
cursor: pointer;
border: 1px solid transparent;
font-size: ${theme.font.code.size.small};
&.${ClassName.SELECTED} {
background: ${
theme.colors.default.primary + theme.default.transparency.low
};
}
&.${ClassName.CTX_SELECTED} {
background: ${
theme.colors.default.primary + theme.default.transparency.low
};
border-color: ${
theme.colors.default.primary + theme.default.transparency.medium
};
border-radius: ${theme.default.borderRadius};
}
&:hover {
background: ${
theme.colors.default.primary + theme.default.transparency.low
};
}
`}
`;
const SectionTopWrapper = styled.div`
${({ theme }) => css`
display: flex;
align-items: center;
margin-left: 1rem;
margin-bottom: 0.25rem;
color: ${theme.colors.default.textSecondary};
&:not(:first-child) {
margin-top: 1rem;
}
& > button {
margin-left: 0.5rem;
}
& > button:nth-child(2) {
margin-left: 0.75rem;
}
`}
`;
const SectionHeader = styled.div`
font-size: ${({ theme }) => theme.font.code.size.large};
`;
const FolderInsideWrapper = styled.div`
&.${ClassName.HIDDEN} {
display: none;
}
`;
const StyledFolder = styled(Folder)`
${({ theme }) => css`
& span {
color: ${theme.colors.default.primary};
margin-left: 0.5rem;
}
& svg {
width: 0.875rem;
height: 0.875rem;
transition: transform ${theme.default.transition.duration.short}
${theme.default.transition.type};
}
&.${ClassName.OPEN} svg {
transform: rotate(90deg);
}
`}
`;
const StyledFile = styled(File)`
& img {
margin-left: 0.125rem;
}
& span {
color: ${({ theme }) => theme.colors.default.textPrimary};
margin-left: 0.375rem;
}
`;
const PaddingLeft = styled.div<{ depth: number }>`
width: ${({ depth }) => depth}rem;
height: 100%;
`;
export default Folders;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/NoWorkspace.tsx
|
import styled from "styled-components";
import Button from "../../../../components/Button";
import Text from "../../../../components/Text";
import { NewWorkspace } from "./Modals";
import { Plus } from "../../../../components/Icons";
import { PgView } from "../../../../utils/pg";
const NoWorkspace = () => {
const newWorkspace = () => PgView.setModal(NewWorkspace);
return (
<Wrapper>
<Text>Start by creating a new project.</Text>
<Button onClick={newWorkspace} fullWidth leftIcon={<Plus />}>
Create a new project
</Button>
</Wrapper>
);
};
const Wrapper = styled.div`
padding: 1.5rem 1rem;
display: flex;
justify-content: center;
flex-direction: column;
& > button {
margin-top: 1rem;
& svg {
margin-right: 0.5rem !important;
}
}
`;
export default NoWorkspace;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/useExplorerContextMenu.tsx
|
import { MouseEvent, useCallback, useState } from "react";
import { DeleteItem, RenameItem } from "./Modals";
import { ClassName, Id } from "../../../../constants";
import {
PgCommand,
PgCommon,
PgExplorer,
PgGlobal,
PgLanguage,
PgView,
} from "../../../../utils/pg";
import { useRenderOnChange } from "../../../../hooks";
export type ItemData = {
[K in
| "isFolder"
| "isProgramFolder"
| "isClient"
| "isClientFolder"
| "isTest"
| "isTestFolder"]?: boolean;
};
export const useExplorerContextMenu = () => {
const [itemData, setItemData] = useState<ItemData>({});
const [ctxSelectedPath, setCtxSelectedPath] = useState("");
const deployState = useRenderOnChange(
PgGlobal.onDidChangeDeployState,
PgGlobal.deployState
);
const handleMenu = useCallback((ev: MouseEvent<HTMLDivElement>) => {
// Add selected style to the item
let itemEl = ev.target as Node;
while (itemEl.nodeName !== "DIV") {
itemEl = itemEl.parentNode!;
}
const selectedEl = itemEl as HTMLDivElement;
// Root dir is not allowed to be selected as it cannot be renamed or deleted
if (selectedEl.id === Id.ROOT_DIR) throw new Error();
const itemType = PgExplorer.getItemTypeFromEl(selectedEl);
if (!itemType) throw new Error();
const itemPath = PgExplorer.getItemPathFromEl(selectedEl)!;
const itemName = PgExplorer.getItemNameFromPath(itemPath);
const itemData: ItemData = {
isFolder: itemType.folder,
isProgramFolder:
itemType.folder && itemName === PgExplorer.PATHS.SRC_DIRNAME,
isClient:
itemType.file &&
PgLanguage.getIsPathJsLike(itemPath) &&
!itemPath.includes(".test"),
isClientFolder:
itemType.folder && itemName === PgExplorer.PATHS.CLIENT_DIRNAME,
isTest:
itemType.file &&
PgLanguage.getIsPathJsLike(itemPath) &&
itemPath.includes(".test"),
isTestFolder:
itemType.folder && itemName === PgExplorer.PATHS.TESTS_DIRNAME,
};
// Convert the `undefined` values to `false` in order to show them only
// when necessary. (`undefined` defaults to `true` for `showCondition`)
for (const key of PgCommon.keys(itemData)) {
itemData[key] ??= false;
}
setItemData(itemData);
const ctxPath = PgExplorer.getItemPathFromEl(selectedEl);
if (ctxPath) setCtxSelectedPath(ctxPath);
PgExplorer.setCtxSelectedEl(selectedEl);
}, []);
const getPath = useCallback(() => {
if (!ctxSelectedPath) {
return PgExplorer.getItemPathFromEl(PgExplorer.getSelectedEl()!)!;
}
return ctxSelectedPath;
}, [ctxSelectedPath]);
// Functions
const ctxNewItem = useCallback(() => {
const ctxSelected = PgExplorer.getElFromPath(getPath())!;
if (!ctxSelected.classList.contains(ClassName.OPEN)) {
ctxSelected.classList.add(ClassName.OPEN);
ctxSelected.nextElementSibling?.classList.remove(ClassName.HIDDEN);
}
PgView.setNewItemPortal(ctxSelected.nextElementSibling);
setTimeout(() => PgExplorer.setCtxSelectedEl(ctxSelected));
}, [getPath]);
const renameItem = useCallback(async () => {
if (PgExplorer.getCtxSelectedEl()) {
await PgView.setModal(<RenameItem path={getPath()} />);
}
}, [getPath]);
const deleteItem = useCallback(async () => {
if (PgExplorer.getCtxSelectedEl()) {
await PgView.setModal(<DeleteItem path={getPath()} />);
}
}, [getPath]);
const addProgram = useCallback(async () => {
await PgExplorer.newItem(
PgCommon.joinPaths(PgExplorer.PATHS.SRC_DIRNAME, "lib.rs")
);
}, []);
const addClient = useCallback(async () => {
await PgCommand.run.run();
}, []);
const addTests = useCallback(async () => {
await PgCommand.test.run();
}, []);
const runBuild = useCallback(async () => {
await PgCommand.build.run();
}, []);
const runDeploy = useCallback(async () => {
await PgCommand.deploy.run();
}, []);
const runClient = useCallback(async () => {
await PgCommand.run.run(getPath());
}, [getPath]);
const runTest = useCallback(async () => {
await PgCommand.test.run(getPath());
}, [getPath]);
const runClientFolder = useCallback(async () => {
await PgCommand.run.run();
}, []);
const runTestFolder = useCallback(async () => {
await PgCommand.test.run();
}, []);
return {
handleMenu,
ctxNewItem,
renameItem,
deleteItem,
addProgram,
addClient,
addTests,
runBuild,
runDeploy,
runClient,
runTest,
runClientFolder,
runTestFolder,
itemData,
deployState,
};
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/useNewItem.tsx
|
import { useCallback } from "react";
import { PgCommon, PgExplorer, PgView } from "../../../../utils/pg";
export const useNewItem = () => {
const newItem = useCallback(async () => {
const selected = PgExplorer.getSelectedEl();
if (selected) {
// Open if selected is a folder
if (PgExplorer.getItemTypeFromEl(selected)?.folder) {
PgExplorer.openFolder(selected);
PgView.setNewItemPortal(selected.nextElementSibling);
} else {
// Selected is a file
// Open all parents
const path = PgExplorer.getItemPathFromEl(selected)!;
PgExplorer.openAllParents(path);
// The parent folder is the parent element
PgView.setNewItemPortal(selected.parentElement);
}
} else {
// Create in the first dir
const projectRootPath = PgExplorer.getProjectRootPath();
const { folders } = PgExplorer.getFolderContent(projectRootPath);
// Create a new `src` dir if there are no folders
if (!folders.length) {
await PgExplorer.newItem(PgExplorer.PATHS.SRC_DIRNAME);
folders.push(PgExplorer.PATHS.SRC_DIRNAME);
// Sleep to give time for the UI to update
await PgCommon.sleep(100);
}
// Select the first folder(prioritize `src`)
const folderName =
folders.find((name) => name === PgExplorer.PATHS.SRC_DIRNAME) ??
folders[0];
const folderPath = PgExplorer.getCanonicalPath(folderName);
const rootFolderEl = PgExplorer.getRootFolderEl()!;
const divs = rootFolderEl.getElementsByTagName("div");
for (const div of divs) {
const path = PgExplorer.getItemPathFromEl(div);
if (path && PgCommon.isPathsEqual(path, folderPath)) {
PgExplorer.setSelectedEl(div);
newItem();
break;
}
}
}
}, []);
return { newItem };
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/index.ts
|
export { default } from "./Explorer";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/useHandleItemState.tsx
|
import { useEffect } from "react";
import { useTheme } from "styled-components";
import { PgCommon, PgExplorer } from "../../../../utils/pg";
/** Manage the item state when the current workspace or file changes. */
export const useHandleItemState = () => {
const theme = useTheme();
useEffect(() => {
const switchWorkspace = PgExplorer.onDidSwitchWorkspace(() => {
// Reset folder open/closed state
PgExplorer.collapseAllFolders();
});
const openParentsAndSelectEl = (path: string) => {
// Open if current file's parents are not opened
PgExplorer.openAllParents(path);
// Change selected element
const newEl = PgExplorer.getElFromPath(path);
if (newEl) {
PgExplorer.setSelectedEl(newEl);
PgExplorer.removeCtxSelectedEl();
}
};
const switchFile = PgExplorer.onDidOpenFile(async (file) => {
if (!file) return;
openParentsAndSelectEl(file.path);
// Sleep before opening parents because switching workspace collapses
// all folders after file switching
await PgCommon.sleep(300);
openParentsAndSelectEl(file.path);
});
return () => {
switchWorkspace.dispose();
switchFile.dispose();
};
//eslint-disable-next-line react-hooks/exhaustive-deps
}, [theme.name]);
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/ExplorerButtons.tsx
|
import { FC } from "react";
import styled from "styled-components";
import Button from "../../../../components/Button";
import Img from "../../../../components/Img";
import { NewItem, Share } from "./Modals";
import { PgExplorer, PgRouter, PgView } from "../../../../utils/pg";
import { useNewItem } from "./useNewItem";
const ExplorerButtons = () => (
<ButtonsWrapper>
<NewItemButton imageName="new_file.png" title="New file" />
<NewItemButton imageName="new_folder.png" title="New folder" />
<NewItem />
<CollapseAllButton />
<ShareButton />
{PgExplorer.isTemporary && <GoBackButton />}
</ButtonsWrapper>
);
const ButtonsWrapper = styled.div`
display: flex;
justify-content: flex-end;
padding: 0.25rem 0.5rem;
& button {
margin: 0.5rem 0;
padding: 0 0.5rem;
}
& button img {
filter: invert(0.5);
}
& button:hover {
color: initial;
background: initial;
& img {
filter: invert(${({ theme }) => (theme.isDark ? 1 : 0)});
}
}
`;
interface ButtonProps {
imageName: string;
title: string;
}
const NewItemButton: FC<ButtonProps> = ({ imageName, title }) => {
const { newItem } = useNewItem();
return (
<Button onClick={newItem} kind="icon" title={title}>
<Img src={getExplorerIconsPath(imageName)} alt={title} />
</Button>
);
};
const CollapseAllButton = () => (
<Button
onClick={() => PgExplorer.collapseAllFolders()}
kind="icon"
title="Collapse folders"
>
<Img src={getExplorerIconsPath("collapse.png")} alt="Collapse folders" />
</Button>
);
const ShareButton = () => (
<Button onClick={() => PgView.setModal(Share)} kind="icon" title="Share">
<Img src={getExplorerIconsPath("share.png")} alt="Share" />
</Button>
);
const GoBackButton = () => (
<Button
onClick={() => PgRouter.navigate()}
kind="icon"
title="Go back to projects"
>
<Img
src={getExplorerIconsPath("back.png")}
alt="Go back to your project"
style={{ height: "0.875rem", width: "0.875rem" }}
/>
</Button>
);
const getExplorerIconsPath = (name: string) => "/icons/explorer/" + name;
export default ExplorerButtons;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Modals/NewItem.tsx
|
import { FC, useCallback, useMemo, useRef, useState } from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
import Input from "../../../../../components/Input";
import LangIcon from "../../../../../components/LangIcon";
import { EventName } from "../../../../../constants";
import { Fn, PgCommon, PgExplorer } from "../../../../../utils/pg";
import {
useKeybind,
useOnClickOutside,
useSetStatic,
} from "../../../../../hooks";
export const NewItem = () => {
const [El, setEl] = useState<Element | null>(null);
useSetStatic(setEl, EventName.VIEW_NEW_ITEM_PORTAL_SET);
const hide = useCallback(() => setEl(null), []);
return El
? ReactDOM.createPortal(<NewItemInput El={El} hide={hide} />, El)
: null;
};
interface NewItemInputProps {
El: Element;
hide: Fn;
}
const NewItemInput: FC<NewItemInputProps> = ({ El, hide }) => {
const [itemName, setItemName] = useState("");
const [error, setError] = useState(false);
const newFileRef = useRef<HTMLDivElement>(null);
useOnClickOutside(newFileRef, hide);
// Handle keybinds
useKeybind(
[
{
keybind: "Enter",
handle: async () => {
if (!itemName) return;
setError(false);
// Check if the command is coming from context menu
const selected =
PgExplorer.getCtxSelectedEl() ?? PgExplorer.getSelectedEl();
const parentPath =
PgExplorer.getParentPathFromEl(selected as HTMLDivElement) ??
PgExplorer.PATHS.ROOT_DIR_PATH;
try {
// Create item
const itemPath = PgExplorer.getCanonicalPath(
PgCommon.joinPaths(parentPath, itemName)
);
await PgExplorer.newItem(itemPath);
// Hide input
hide();
// Reset Ctx Selected
PgExplorer.removeCtxSelectedEl();
// Select new file
const newEl = PgExplorer.getElFromPath(itemPath);
if (newEl) PgExplorer.setSelectedEl(newEl);
} catch (e: any) {
console.log(e.message);
setError(true);
}
},
},
{
keybind: "Escape",
handle: hide,
},
],
[itemName]
);
const depth = useMemo(() => {
if (!El) return 0;
let path = PgExplorer.getItemPathFromEl(El.firstChild as HTMLDivElement);
const isEmptyFolder = !path;
// Empty folder
if (!path) {
path = PgExplorer.getItemPathFromEl(
El.parentElement?.firstChild as HTMLDivElement
);
if (!path) return 2;
}
const itemType = PgExplorer.getItemTypeFromPath(path);
// Make `path` relative for consistency between temporary and normal projects
if (PgExplorer.isTemporary) path = path.slice(1);
else path = PgExplorer.getRelativePath(path);
return path.split("/").length - (itemType.file || isEmptyFolder ? 0 : 1);
}, [El]);
return (
<Wrapper ref={newFileRef} depth={depth}>
<LangIcon path={itemName} />
<Input
autoFocus
value={itemName}
onChange={(ev) => {
setItemName(ev.target.value);
setError(false);
}}
error={error}
setError={setError}
/>
</Wrapper>
);
};
const Wrapper = styled.div<{ depth: number }>`
display: flex;
align-items: center;
padding: 0.25rem 0;
padding-left: ${({ depth }) => depth + "rem"};
& > input {
height: 1.5rem;
margin-left: 0.375rem;
}
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Modals/ReplaceItem.tsx
|
import { FC } from "react";
import styled, { css } from "styled-components";
import Modal from "../../../../../components/Modal";
import { Warning } from "../../../../../components/Icons";
import { PgExplorer } from "../../../../../utils/pg";
interface ReplaceItemProps {
fromPath: string;
toPath: string;
}
export const ReplaceItem: FC<ReplaceItemProps> = ({ fromPath, toPath }) => {
const itemName = PgExplorer.getItemNameFromPath(toPath);
const replaceItem = async () => {
await PgExplorer.renameItem(fromPath, toPath, {
skipNameValidation: true,
override: true,
});
};
return (
<Modal
title
buttonProps={{
text: "Replace",
onSubmit: replaceItem,
}}
>
<Content>
<Icon>
<Warning color="warning" />
</Icon>
<ContentText>
<Main>'{itemName}' already exists. Do you want to replace it?</Main>
<Desc>This action is irreversable.</Desc>
</ContentText>
</Content>
</Modal>
);
};
const Content = styled.div`
display: flex;
justify-content: center;
align-items: center;
`;
const Icon = styled.div`
width: 2rem;
height: 2rem;
& > svg {
width: 100%;
height: 100%;
}
`;
const ContentText = styled.div`
display: flex;
flex-direction: column;
margin-left: 1rem;
`;
const Main = styled.span`
font-weight: bold;
`;
const Desc = styled.span`
${({ theme }) => css`
margin-top: 0.5rem;
font-size: ${theme.font.code.size.small};
color: ${theme.colors.default.textSecondary};
`}
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Modals/DeleteWorkspace.tsx
|
import styled, { css } from "styled-components";
import Modal from "../../../../../components/Modal";
import { Warning } from "../../../../../components/Icons";
import { PgExplorer } from "../../../../../utils/pg";
export const DeleteWorkspace = () => {
const deleteWorkspace = async () => {
await PgExplorer.deleteWorkspace();
};
return (
<Modal
title
buttonProps={{
text: "Delete",
onSubmit: deleteWorkspace,
kind: "error",
}}
>
<Content>
<IconWrapper>
<Warning color="warning" />
</IconWrapper>
<ContentText>
<Main>
Are you sure you want to delete workspace '
{PgExplorer.currentWorkspaceName}'?
</Main>
<Desc>This action is irreversable!</Desc>
<Desc>- All files and folders will be deleted.</Desc>
<Desc>- Program credentials will be deleted.</Desc>
</ContentText>
</Content>
</Modal>
);
};
const Content = styled.div`
display: flex;
justify-content: center;
align-items: center;
`;
const IconWrapper = styled.div`
& > svg {
width: 3rem;
height: 3rem;
}
`;
const ContentText = styled.div`
display: flex;
flex-direction: column;
margin-left: 1rem;
`;
const Main = styled.span`
font-weight: bold;
word-break: break-all;
`;
const Desc = styled.span`
${({ theme }) => css`
margin-top: 0.5rem;
font-size: ${theme.font.code.size.small};
color: ${theme.colors.default.textSecondary};
`}
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Modals/Share.tsx
|
import { FC, useState } from "react";
import styled from "styled-components";
import CopyButton from "../../../../../components/CopyButton";
import FilePicker from "../../../../../components/FilePicker";
import Input from "../../../../../components/Input";
import Link from "../../../../../components/Link";
import Modal from "../../../../../components/Modal";
import Text from "../../../../../components/Text";
import { Checkmark, Sad } from "../../../../../components/Icons";
import { PgCommon, PgExplorer, PgShare, PgView } from "../../../../../utils/pg";
export const Share = () => {
const [filePaths, setFilePaths] = useState(() =>
Object.keys(PgExplorer.files).filter(
(path) => PgExplorer.getItemTypeFromPath(path).file
)
);
const share = async () => {
try {
const shareId = await PgCommon.transition(PgShare.new(filePaths));
PgView.setModal(<SuccessPage shareId={shareId} />);
} catch (e: any) {
console.log("SHARE ERROR:", e.message);
PgView.setModal(<ErrorPage message={e.message} />);
}
};
return (
<Modal
title
buttonProps={{
text: "Share",
onSubmit: share,
disabled: !filePaths.length,
noCloseOnSubmit: true,
}}
>
<SelectFilesText>Select the files you'd like to share.</SelectFilesText>
<FilePicker
path={PgExplorer.getProjectRootPath()}
filePaths={filePaths}
setFilePaths={setFilePaths}
/>
</Modal>
);
};
const SelectFilesText = styled.div`
margin-bottom: 1rem;
`;
interface ErrorPageProps {
message: string;
}
const ErrorPage: FC<ErrorPageProps> = ({ message }) => (
<Modal title buttonProps={{ text: "Continue" }}>
<Text kind="error" icon={<Sad />}>
Share error: {message}
</Text>
</Modal>
);
interface SuccessPageProps {
shareId: string;
}
const SuccessPage: FC<SuccessPageProps> = ({ shareId }) => {
const shareLink = PgCommon.getPathUrl(shareId);
return (
<Modal title buttonProps={{ text: "Continue" }}>
<SuccessWrapper>
<Text kind="success" icon={<Checkmark color="success" />}>
Successfully shared the project.
</Text>
<SuccessInputWrapper>
<Input value={shareLink} readOnly />
<CopyButton copyText={shareLink} />
</SuccessInputWrapper>
<SuccessLinkWrapper>
<Link href={shareLink}>Go to the link</Link>
</SuccessLinkWrapper>
</SuccessWrapper>
</Modal>
);
};
const SuccessWrapper = styled.div`
min-width: 24rem;
`;
const SuccessInputWrapper = styled.div`
display: flex;
margin-top: 1rem;
align-items: center;
`;
const SuccessLinkWrapper = styled.div`
display: flex;
justify-content: flex-start;
margin-top: 0.75rem;
margin-left: 0.25rem;
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Modals/ExportWorkspaceReadme.tsx
|
/** Separate file in order to lazy load `Markdown` component */
import { FC } from "react";
import Markdown from "../../../../../components/Markdown";
import Modal from "../../../../../components/Modal";
interface ExportWorkspaceReadmeProps {
/** Markdown text */
text: string;
}
export const ExportWorkspaceReadme: FC<ExportWorkspaceReadmeProps> = ({
text,
}) => (
<Modal title buttonProps={{ text: "Continue" }}>
<Markdown>{text}</Markdown>
</Modal>
);
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Modals/ExportWorkspace.tsx
|
import styled, { css } from "styled-components";
import Button from "../../../../../components/Button";
import Modal from "../../../../../components/Modal";
import Text from "../../../../../components/Text";
import { ExportFile, Info } from "../../../../../components/Icons";
import { PgFramework, PgView } from "../../../../../utils/pg";
export const ExportWorkspace = () => {
const convertAndExport = async () => {
try {
const { readme } = await PgFramework.exportWorkspace({ convert: true });
const { ExportWorkspaceReadme } = await import("./ExportWorkspaceReadme");
await PgView.setModal(<ExportWorkspaceReadme text={readme!} />);
} catch (e) {
console.error("Convert and export error:", e);
await exportWithoutChanges();
}
};
const exportWithoutChanges = async () => {
await PgFramework.exportWorkspace();
PgView.closeModal();
};
return (
<Modal title="Export project">
<Content>
<Question>Convert the project layout?</Question>
<Description>
Playground uses a different layout than the framework's default
layout.
</Description>
<Description>
To make the project work locally, playground can make the necessary
conversion before exporting.
</Description>
<InfoText icon={<Info color="info" />}>
Conversion may involve modifying JS/TS code to make the code work in
local Node environment.
</InfoText>
<ButtonsWrapper>
<Button
onClick={convertAndExport}
kind="primary-transparent"
rightIcon={<ExportFile />}
>
Convert and export
</Button>
<Button onClick={exportWithoutChanges} rightIcon={<ExportFile />}>
Export without changes
</Button>
</ButtonsWrapper>
</Content>
</Modal>
);
};
const Content = styled.div`
max-width: 26rem;
`;
const Question = styled.p`
font-weight: bold;
`;
const Description = styled.p`
${({ theme }) => css`
color: ${theme.colors.default.textSecondary};
font-size: ${theme.font.code.size.small};
margin-top: 1rem;
`}
`;
const InfoText = styled(Text)`
margin-top: 1rem;
`;
const ButtonsWrapper = styled.div`
display: flex;
margin-top: 1rem;
& > * {
margin-right: 1rem;
}
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Modals/ImportGithub.tsx
|
import { ChangeEvent, FC, useState } from "react";
import styled, { css } from "styled-components";
import Button from "../../../../../components/Button";
import Img from "../../../../../components/Img";
import Input from "../../../../../components/Input";
import Link from "../../../../../components/Link";
import Modal from "../../../../../components/Modal";
import Text from "../../../../../components/Text";
import {
Eye,
Github,
ImportWorkspace,
Info,
} from "../../../../../components/Icons";
import {
Framework,
PgCommon,
PgFramework,
PgGithub,
PgRouter,
PgView,
} from "../../../../../utils/pg";
export const ImportGithub = () => {
// Handle user input
const [url, setUrl] = useState("");
const [error, setError] = useState("");
const handleChange = (ev: ChangeEvent<HTMLInputElement>) => {
const input = ev.target.value;
setUrl(input);
if (!input.includes("github.com")) setError("The URL must be a GitHub URL");
else setError("");
};
const importFromGithub = () => PgCommon.transition(PgGithub.import(url));
return (
<Modal
title
buttonProps={{
text: "Import",
onSubmit: importFromGithub,
disabled: !url,
btnLoading: { text: "Importing..." },
rightIcon: <ImportWorkspace />,
}}
error={error}
setError={setError}
>
<Wrapper>
<GithubUrlWrapper>
<GithubUrlInputLabel>GitHub URL</GithubUrlInputLabel>
<Input
autoFocus
onChange={handleChange}
value={url}
validator={PgGithub.isValidUrl}
setError={setError}
placeholder="https://github.com/..."
/>
</GithubUrlWrapper>
<Description>
Projects can be imported or viewed from their GitHub URL.
</Description>
<ExamplesSectionWrapper>
<ExamplesTitle>Examples</ExamplesTitle>
<ExamplesWrapper>
{PgFramework.all.map((framework) => (
<Example key={framework.name} framework={framework} />
))}
</ExamplesWrapper>
</ExamplesSectionWrapper>
<Text icon={<Info color="info" />}>
<p>
Program repositories can be viewed in playground by combining the
playground URL with their GitHub URL. For example, from{" "}
<Link href={GITHUB_PROGRAM_URL}>this repository</Link>:
</p>
<p style={{ wordBreak: "break-all" }}>
<Link href={VIEW_URL}>{VIEW_URL}</Link>
</p>
</Text>
</Wrapper>
</Modal>
);
};
const GITHUB_PROGRAM_URL =
"https://github.com/solana-developers/program-examples/tree/main/basics/create-account/anchor";
const VIEW_URL = PgCommon.getPathUrl(GITHUB_PROGRAM_URL);
const Wrapper = styled.div`
max-width: 39rem;
`;
const GithubUrlWrapper = styled.div``;
const GithubUrlInputLabel = styled.div`
margin-bottom: 0.5rem;
font-weight: bold;
`;
const Description = styled.div`
${({ theme }) => css`
margin: 1rem 0;
font-size: ${theme.font.code.size.small};
color: ${theme.colors.default.textSecondary};
word-break: break-all;
`}
`;
const ExamplesSectionWrapper = styled.div`
margin: 1rem 0;
`;
const ExamplesTitle = styled.div`
font-weight: bold;
`;
const ExamplesWrapper = styled.div`
margin-top: 0.5rem;
`;
interface ExampleProps {
framework: Framework;
}
const Example: FC<ExampleProps> = ({ framework }) => (
<ExampleWrapper>
<FrameworkWrapper>
<FrameworkImage src={framework.icon} $circle={framework.circleImage} />
<FrameworkName>
{framework.name} - {framework.githubExample.name}
</FrameworkName>
</FrameworkWrapper>
<ExampleButtonsWrapper>
<Button
onClick={async () => {
await PgGithub.import(framework.githubExample.url);
PgView.closeModal();
}}
rightIcon={<ImportWorkspace />}
>
Import
</Button>
<Button
onClick={() => {
PgRouter.navigate("/" + framework.githubExample.url);
PgView.closeModal();
}}
rightIcon={<Eye />}
>
Open
</Button>
<Link href={framework.githubExample.url}>
<Button rightIcon={<Github />}>Open in GitHub</Button>
</Link>
</ExampleButtonsWrapper>
</ExampleWrapper>
);
const ExampleWrapper = styled.div`
margin: 1rem 0;
display: flex;
justify-content: space-between;
align-items: center;
`;
const ExampleButtonsWrapper = styled.div`
display: flex;
& > * {
margin-left: 1.5rem;
}
`;
const FrameworkWrapper = styled.div`
${({ theme }) => css`
padding: 0.5rem 1rem;
width: fit-content;
display: flex;
align-items: center;
justify-content: center;
border-radius: ${theme.default.borderRadius};
`}
`;
const FrameworkImage = styled(Img)<{ $circle?: boolean }>`
${({ $circle }) => css`
width: 1rem;
height: 1rem;
border-radius: ${$circle && "50%"};
`}
`;
const FrameworkName = styled.span`
margin-left: 0.5rem;
font-weight: bold;
color: ${({ theme }) => theme.colors.default.textSecondary};
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Modals/RenameWorkspace.tsx
|
import { ChangeEvent, useEffect, useRef, useState } from "react";
import Input from "../../../../../components/Input";
import Modal from "../../../../../components/Modal";
import { PgCommon, PgExplorer, PgView } from "../../../../../utils/pg";
export const RenameWorkspace = () => {
const workspaceName = PgExplorer.currentWorkspaceName!;
const [newName, setNewName] = useState(workspaceName);
const [error, setError] = useState("");
const handleChange = (ev: ChangeEvent<HTMLInputElement>) => {
setNewName(ev.target.value);
setError("");
};
const renameWorkspace = async () => {
if (PgExplorer.currentWorkspaceName === newName) return;
try {
PgView.setSidebarLoading(true);
await PgCommon.transition(PgExplorer.renameWorkspace(newName));
} finally {
PgView.setSidebarLoading(false);
}
};
// Select input text on mount
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.select();
}, []);
return (
<Modal
title={`Rename workspace '${workspaceName}'`}
buttonProps={{
text: "Rename",
onSubmit: renameWorkspace,
disabled: !newName,
size: "small",
}}
error={error}
setError={setError}
>
<Input
ref={inputRef}
onChange={handleChange}
value={newName}
error={error}
setError={setError}
validator={PgExplorer.isWorkspaceNameValid}
/>
</Modal>
);
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Modals/NewWorkspace.tsx
|
import { ChangeEvent, FC, useState } from "react";
import styled, { css } from "styled-components";
import Img from "../../../../../components/Img";
import Input from "../../../../../components/Input";
import Modal from "../../../../../components/Modal";
import {
Fn,
Framework as FrameworkType,
PgExplorer,
PgFramework,
} from "../../../../../utils/pg";
export const NewWorkspace = () => {
// Handle user input
const [name, setName] = useState("");
const [error, setError] = useState("");
const [selected, setSelected] = useState<string | null>(null);
const handleChange = (ev: ChangeEvent<HTMLInputElement>) => {
setName(ev.target.value);
setError("");
};
const newWorkspace = async () => {
const { importFiles, defaultOpenFile } = PgFramework.all.find(
(f) => f.name === selected
)!;
const { files } = await importFiles();
await PgExplorer.newWorkspace(name, {
files,
defaultOpenFile,
});
};
return (
<Modal
buttonProps={{
text: "Create",
onSubmit: newWorkspace,
disabled: !name || !selected,
}}
error={error}
setError={setError}
>
<Content>
<WorkspaceNameWrapper>
<MainText>Project name</MainText>
<Input
autoFocus
onChange={handleChange}
value={name}
error={error}
setError={setError}
validator={PgExplorer.isWorkspaceNameValid}
placeholder="my project..."
/>
</WorkspaceNameWrapper>
<FrameworkSectionWrapper>
<MainText>Choose a framework</MainText>
<FrameworksWrapper>
{PgFramework.all.map((f) => (
<Framework
key={f.name}
isSelected={selected === f.name}
select={() =>
setSelected((s) => (s === f.name ? null : f.name))
}
{...f}
/>
))}
</FrameworksWrapper>
</FrameworkSectionWrapper>
</Content>
</Modal>
);
};
const Content = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
`;
const WorkspaceNameWrapper = styled.div``;
const MainText = styled.div`
margin-bottom: 0.5rem;
font-weight: bold;
font-size: ${({ theme }) => theme.font.code.size.large};
`;
const FrameworkSectionWrapper = styled.div`
margin: 1rem 0 0.5rem 0;
`;
const FrameworksWrapper = styled.div`
display: flex;
gap: 2rem;
`;
interface FrameworkProps extends FrameworkType {
isSelected: boolean;
select: Fn;
}
const Framework: FC<FrameworkProps> = ({
name,
language,
icon,
circleImage,
isSelected,
select,
}) => (
<FrameworkWrapper isSelected={isSelected} onClick={select}>
<FrameworkImageWrapper circle={circleImage}>
<Img src={icon} alt={name} />
</FrameworkImageWrapper>
<FrameworkName>
{name}({language})
</FrameworkName>
</FrameworkWrapper>
);
const FrameworkWrapper = styled.div<{ isSelected?: boolean }>`
${({ theme, isSelected }) => css`
width: fit-content;
padding: 1rem;
border: 1px solid ${theme.colors.default.border};
border-radius: ${theme.default.borderRadius};
transition: all ${theme.default.transition.duration.medium}
${theme.default.transition.type};
border-color: ${isSelected && theme.colors.default.primary};
& div:nth-child(2) {
color: ${isSelected && theme.colors.default.textPrimary};
}
&:hover {
cursor: pointer;
border-color: ${!isSelected && theme.colors.default.textPrimary};
& div:nth-child(2) {
color: ${theme.colors.default.textPrimary};
}
}
`}
`;
const FrameworkImageWrapper = styled.div<{ circle?: boolean }>`
${({ circle }) => css`
width: 8rem;
height: 8rem;
display: flex;
align-items: center;
& > img {
width: 100%;
border-radius: ${circle && "50%"};
}
`}
`;
const FrameworkName = styled.div`
margin-top: 0.75rem;
text-align: center;
font-weight: bold;
color: ${({ theme }) => theme.colors.default.textSecondary};
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Modals/index.ts
|
export { DeleteItem } from "./DeleteItem";
export { DeleteWorkspace } from "./DeleteWorkspace";
export { ExportWorkspace } from "./ExportWorkspace";
export { ImportFs } from "./ImportFs";
export { ImportGithub } from "./ImportGithub";
export { ImportTemporary } from "./ImportTemporary";
export { NewItem } from "./NewItem";
export { NewWorkspace } from "./NewWorkspace";
export { RenameItem } from "./RenameItem";
export { RenameWorkspace } from "./RenameWorkspace";
export { ReplaceItem } from "./ReplaceItem";
export { Share } from "./Share";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Modals/DeleteItem.tsx
|
import { FC } from "react";
import styled, { css } from "styled-components";
import Modal from "../../../../../components/Modal";
import { Warning } from "../../../../../components/Icons";
import { PgCommon, PgExplorer } from "../../../../../utils/pg";
interface DeleteItemProps {
path: string;
}
export const DeleteItem: FC<DeleteItemProps> = ({ path }) => {
const itemName = PgExplorer.getItemNameFromPath(path);
const deleteItem = async () => {
await PgExplorer.deleteItem(path);
// Select element if there is no selected element
if (!PgExplorer.getSelectedEl()) {
const itemPathToSelect =
PgExplorer.currentFilePath ??
PgCommon.appendSlash(
PgCommon.joinPaths(
PgExplorer.getProjectRootPath(),
PgExplorer.PATHS.SRC_DIRNAME
)
);
const itemToSelect = PgExplorer.getElFromPath(itemPathToSelect);
if (itemToSelect) PgExplorer.setSelectedEl(itemToSelect);
}
};
return (
<Modal
title
buttonProps={{
text: "Delete",
onSubmit: deleteItem,
kind: "error",
}}
>
<Content>
<Icon>
<Warning color="warning" />
</Icon>
<ContentText>
<Main>Are you sure you want to delete '{itemName}'?</Main>
<Desc>This action is irreversable.</Desc>
</ContentText>
</Content>
</Modal>
);
};
const Content = styled.div`
display: flex;
justify-content: center;
align-items: center;
`;
const Icon = styled.div`
width: 2rem;
height: 2rem;
& > svg {
width: 100%;
height: 100%;
}
`;
const ContentText = styled.div`
display: flex;
flex-direction: column;
margin-left: 1rem;
`;
const Main = styled.span`
font-weight: bold;
`;
const Desc = styled.span`
${({ theme }) => css`
margin-top: 0.5rem;
font-size: ${theme.font.code.size.small};
color: ${theme.colors.default.textSecondary};
`}
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Modals/ImportTemporary.tsx
|
import { ChangeEvent, useState } from "react";
import styled from "styled-components";
import Input from "../../../../../components/Input";
import Modal from "../../../../../components/Modal";
import { PgExplorer } from "../../../../../utils/pg";
export const ImportTemporary = () => {
const [name, setName] = useState("");
const [error, setError] = useState("");
const handleChange = (ev: ChangeEvent<HTMLInputElement>) => {
setName(ev.target.value);
setError("");
};
const importTemporary = async () => {
await PgExplorer.newWorkspace(name, { fromTemporary: true });
};
return (
<Modal
title
buttonProps={{
text: "Import",
onSubmit: importTemporary,
disabled: !name,
}}
error={error}
setError={setError}
>
<MainText>Project name</MainText>
<Input
autoFocus
onChange={handleChange}
value={name}
error={error}
setError={setError}
validator={PgExplorer.isWorkspaceNameValid}
placeholder="project name..."
/>
</Modal>
);
};
const MainText = styled.div`
margin-bottom: 0.5rem;
font-weight: bold;
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Modals/RenameItem.tsx
|
import { ChangeEvent, FC, useEffect, useRef, useState } from "react";
import Input from "../../../../../components/Input";
import Modal from "../../../../../components/Modal";
import { PgCommon, PgExplorer } from "../../../../../utils/pg";
interface RenameItemProps {
path: string;
}
export const RenameItem: FC<RenameItemProps> = ({ path }) => {
const itemName = PgExplorer.getItemNameFromPath(path);
const [newName, setNewName] = useState(itemName);
const [error, setError] = useState("");
const handleChange = (ev: ChangeEvent<HTMLInputElement>) => {
setNewName(ev.target.value);
setError("");
};
const rename = async () => {
const newPath = PgCommon.joinPaths(
PgExplorer.getParentPathFromPath(path),
newName
);
await PgExplorer.renameItem(path, newPath);
};
// Select the file name without the extension on mount
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.setSelectionRange(0, inputRef.current.value.indexOf("."));
}, []);
return (
<Modal
title={`Rename '${itemName}'`}
buttonProps={{
text: "Rename",
onSubmit: rename,
size: "small",
disabled: !newName,
}}
error={error}
setError={setError}
>
<Input
ref={inputRef}
autoFocus
value={newName}
onChange={handleChange}
error={error}
setError={setError}
validator={PgExplorer.isItemNameValid}
/>
</Modal>
);
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/explorer/Component/Modals/ImportFs.tsx
|
import { ChangeEvent, FC, useState } from "react";
import styled from "styled-components";
import Input from "../../../../../components/Input";
import Modal from "../../../../../components/Modal";
import Text from "../../../../../components/Text";
import UploadArea from "../../../../../components/UploadArea";
import { ImportWorkspace, Info } from "../../../../../components/Icons";
import {
PgExplorer,
PgFramework,
PgView,
TupleFiles,
} from "../../../../../utils/pg";
import { useMounted } from "../../../../../hooks";
interface ImportFsProps {
name?: string;
files?: TupleFiles;
filesError?: string;
}
export const ImportFs: FC<ImportFsProps> = (props) => {
// Handle user input
const [name, setName] = useState(props.name ?? "");
const [files, setFiles] = useState(props.files);
const [filesError, setFilesError] = useState(props.filesError ?? "");
const [importError, setImportError] = useState("");
const mounted = useMounted();
const handleChange = (ev: ChangeEvent<HTMLInputElement>) => {
setName(ev.target.value);
setImportError("");
};
const onDrop = async (userFiles: Array<File & { path: string }>) => {
try {
const importFiles: TupleFiles = [];
for (const userFile of userFiles) {
let path = userFile.path;
const shouldSkip = /(\/\.|node_modules|target)/.test(path);
if (shouldSkip) continue;
const content = await userFile.text();
importFiles.push([path, content]);
}
const pgFiles = await PgFramework.convertToPlaygroundLayout(importFiles);
// Multiple programs require selecting the program to import which closes
// the current modal
if (!mounted.current) {
PgView.setModal(<ImportFs name={name} files={pgFiles} />);
} else {
setFiles(pgFiles);
setFilesError("");
}
} catch (e: any) {
if (!mounted.current) {
PgView.setModal(<ImportFs name={name} filesError={e.message} />);
} else {
setFilesError(e.message);
}
}
};
const importFs = () => PgExplorer.newWorkspace(name, { files });
return (
<Modal
title="Import project"
buttonProps={{
text: "Import",
onSubmit: importFs,
disabled: !name || !files || !!filesError,
rightIcon: <ImportWorkspace />,
}}
error={importError}
setError={setImportError}
>
<Content>
<ProjectNameWrapper>
<MainText>Project name</MainText>
<Input
autoFocus
onChange={handleChange}
value={name}
error={importError}
placeholder="my local project..."
/>
</ProjectNameWrapper>
<UploadAreaWrapper>
<UploadArea
onDrop={onDrop}
error={filesError}
filesLength={files?.length}
text="Drop a program or a workspace"
/>
</UploadAreaWrapper>
<StyledText icon={<Info color="info" />}>
You can drag & drop a Cargo workspace directory.
</StyledText>
</Content>
</Modal>
);
};
const Content = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
`;
const ProjectNameWrapper = styled.div`
margin-bottom: 0.25rem;
`;
const MainText = styled.div`
margin-bottom: 0.5rem;
font-weight: bold;
`;
const UploadAreaWrapper = styled.div`
margin-top: 1rem;
`;
const StyledText = styled(Text)`
margin-top: 1rem;
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/programs/programs.ts
|
import { createSidebarPage } from "../create";
export const programs = createSidebarPage({
name: "Programs",
icon: "program.png",
keybind: "Ctrl+Shift+P",
route: "/programs",
});
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/programs/index.ts
|
export { programs } from "./programs";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/programs
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/programs/Component/Programs.tsx
|
import styled, { css } from "styled-components";
import FilterGroups from "../../../../components/FilterGroups";
import { FILTERS } from "../../../main/primary/Programs/filters";
const Programs = () => (
<Wrapper>
<FilterGroups filters={FILTERS} />
</Wrapper>
);
const Wrapper = styled.div`
${({ theme }) => css`
font-family: ${theme.font.other.family};
font-size: ${theme.font.other.size.medium};
`}
`;
export default Programs;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/programs
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/programs/Component/index.ts
|
export { default } from "./Programs";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/tutorials/index.ts
|
export { tutorials } from "./tutorials";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/tutorials/tutorials.ts
|
import TutorialsSkeleton from "./Component/TutorialsSkeleton";
import { createSidebarPage } from "../create";
export const tutorials = createSidebarPage({
name: "Tutorials",
icon: "tutorials.webp",
keybind: "Ctrl+Shift+X",
route: "/tutorials",
LoadingElement: TutorialsSkeleton,
});
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/tutorials/Component/index.ts
|
export { default } from "./Tutorials";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/tutorials/Component/Tutorials.tsx
|
import { FC, useState } from "react";
import styled, { css, keyframes } from "styled-components";
import TutorialsSkeleton from "./TutorialsSkeleton";
import Text from "../../../../components/Text";
import {
PgCommon,
PgTutorial,
TutorialData,
TutorialMetadata,
} from "../../../../utils/pg";
import { useAsyncEffect } from "../../../../hooks";
type TutorialFullData = (TutorialData & TutorialMetadata)[];
type TutorialsData = { completed: TutorialFullData; ongoing: TutorialFullData };
const Tutorials = () => {
const [tutorialsData, setTutorialsData] = useState<TutorialsData>();
// Get tutorial data
useAsyncEffect(async () => {
// Sleep here because:
// - If user starts on the `tutorials` route, the workspaces might not get
// initialized before this callback runs which causes errors while getting
// tutorial names with `PgTutorial.getUserTutorialNames`
// - The current tutorial's `completed` state might not have been saved yet
// after finishing the tutorial
// - Better transition
await PgCommon.sleep(300);
const tutorialNames = PgTutorial.getUserTutorialNames();
const data: TutorialsData = { completed: [], ongoing: [] };
for (const tutorialName of tutorialNames) {
const tutorialData = PgTutorial.getTutorialData(tutorialName);
if (!tutorialData) continue;
const tutorialMetadata = await PgTutorial.getMetadata(tutorialName);
const tutorialFullData = { ...tutorialData, ...tutorialMetadata };
if (tutorialMetadata.completed) data.completed.push(tutorialFullData);
else data.ongoing.push(tutorialFullData);
}
setTutorialsData(data);
}, []);
if (!tutorialsData) return <TutorialsSkeleton />;
return (
<Wrapper>
{!tutorialsData.ongoing.length && !tutorialsData.completed.length && (
<Text>Choose and start a new tutorial to track your progress.</Text>
)}
<TutorialGroup name="Ongoing" data={tutorialsData.ongoing} />
<TutorialGroup name="Completed" data={tutorialsData.completed} />
</Wrapper>
);
};
const Wrapper = styled.div`
${({ theme }) => css`
padding: 1.5rem 1rem;
color: ${theme.colors.default.textSecondary};
`}
`;
interface TutorialGroupProps {
name: string;
data: TutorialFullData;
}
const TutorialGroup: FC<TutorialGroupProps> = ({ name, data }) => (
<>
{data.length > 0 && (
<TutorialsSectionHeader>
{name} -> <Bold>{data.length}</Bold>
</TutorialsSectionHeader>
)}
{data.map((t, i) => (
<TutorialWrapper
key={i}
onClick={() => PgTutorial.open(t.name)}
progress={t.completed ? 100 : ((t.pageNumber - 1) / t.pageCount) * 100}
>
<TutorialName>{t.name}</TutorialName>
</TutorialWrapper>
))}
</>
);
const TutorialsSectionHeader = styled.div`
font-size: ${({ theme }) => theme.font.code.size.large};
&:not(:first-child) {
margin-top: 2rem;
}
`;
const Bold = styled.span`
font-weight: bold;
`;
const TutorialWrapper = styled.div<{ progress: number }>`
${({ theme, progress }) => css`
margin-top: 1rem;
padding: 0.75rem 1rem;
background: ${theme.components.sidebar.right.default.otherBg};
border-radius: ${theme.default.borderRadius};
box-shadow: ${theme.default.boxShadow};
transition: all ${theme.default.transition.duration.medium}
${theme.default.transition.type};
position: relative;
&::after {
content: "";
position: absolute;
bottom: 0;
left: 0;
height: 0.125rem;
background: ${progress === 100
? `linear-gradient(90deg, ${theme.colors.state.success.color} 0%, ${
theme.colors.state.success.color + theme.default.transparency.high
} 100%)`
: `linear-gradient(90deg, ${theme.colors.default.primary} 0%, ${theme.colors.default.secondary} 100%)`};
animation: ${animateWidth(progress)}
${theme.default.transition.duration.long}
${theme.default.transition.type} forwards;
}
&:hover {
background: ${theme.colors.state.hover.bg};
color: ${theme.colors.default.textPrimary};
cursor: pointer;
}
`}
`;
const animateWidth = (progress: number) =>
keyframes`
from {
width: 0;
}
to {
width: ${progress}%;
}
`;
const TutorialName = styled.div`
font-weight: bold;
`;
export default Tutorials;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/tutorials/Component/TutorialsSkeleton.tsx
|
import styled from "styled-components";
import { Skeleton } from "../../../../components/Loading";
const TutorialsSkeleton = () => (
<Wrapper>
<OngoingWrapper>
<Heading>
<Skeleton width="7rem" />
</Heading>
<Tutorial>
<Skeleton height="2.625rem" />
</Tutorial>
</OngoingWrapper>
<CompletedWrapper>
<Heading>
<Skeleton width="8rem" />
</Heading>
<Tutorial>
<Skeleton height="2.625rem" />
</Tutorial>
</CompletedWrapper>
</Wrapper>
);
const Wrapper = styled.div``;
const Heading = styled.div`
padding: 1rem 0 0 1rem;
`;
const Tutorial = styled.div`
margin: 1rem 1rem 0 1rem;
`;
const OngoingWrapper = styled.div`
margin-top: 0.625rem;
`;
const CompletedWrapper = styled.div`
margin-top: 1.125rem;
`;
export default TutorialsSkeleton;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/index.ts
|
export { MAIN_SECONDARY } from "./secondary";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary/NotFound/index.ts
|
export { NotFound } from "./NotFound";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary/NotFound/NotFound.tsx
|
import type { FC } from "react";
import styled from "styled-components";
import Button from "../../../../components/Button";
import Text from "../../../../components/Text";
import { Error } from "../../../../components/Icons";
import { PgRouter } from "../../../../utils/pg";
interface NotFoundProps {
path: string;
}
export const NotFound: FC<NotFoundProps> = ({ path }) => (
<Wrapper>
<Text kind="error" icon={<Error />}>
Invalid URL path: {path}
</Text>
<Button kind="primary-transparent" onClick={() => PgRouter.navigate()}>
Go home
</Button>
</Wrapper>
);
const Wrapper = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 1rem;
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary/Programs/filters.ts
|
import { PgFramework, TUTORIAL_CATEGORIES } from "../../../../utils/pg";
/** All program filters */
export const FILTERS = [
{
param: "framework",
filters: PgFramework.all.map((f) => f.name),
},
{
param: "categories",
filters: TUTORIAL_CATEGORIES.filter((c) => c !== "Gaming"),
},
] as const;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary/Programs/Programs.tsx
|
import { FC } from "react";
import styled, { css } from "styled-components";
import SearchBar from "../../../../components/SearchBar";
import Text from "../../../../components/Text";
import ProgramCard, { ProgramCardProps } from "./ProgramCard";
import { FILTERS } from "./filters";
import { Sad } from "../../../../components/Icons";
import { useFilteredSearch } from "../../../../hooks";
import { PgTheme } from "../../../../utils/pg";
interface ProgramsProps {
programs: ProgramCardProps[];
}
export const Programs: FC<ProgramsProps> = ({ programs }) => {
const filteredSearch = useFilteredSearch({
route: "/programs",
items: programs,
filters: FILTERS,
sort: (a, b) => a.name.localeCompare(b.name),
});
if (!filteredSearch) return null;
const { regularItems, searchBarProps } = filteredSearch;
return (
<Wrapper>
<TopSection>
<Title>Programs</Title>
<SearchBar
{...searchBarProps}
placeholder="Search programs"
searchButton={{ position: "right", width: "2.5rem" }}
/>
</TopSection>
<MainSection>
<MainContent noMatch={!regularItems.length}>
{!regularItems.length && (
<NoMatchText icon={<Sad />}>No match found</NoMatchText>
)}
{regularItems.map((program) => (
<ProgramCard key={program.name} {...program} />
))}
</MainContent>
</MainSection>
</Wrapper>
);
};
const Wrapper = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(theme.components.main.primary.programs.default)};
`}
`;
const TopSection = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(theme.components.main.primary.programs.top)};
`}
`;
const Title = styled.h1``;
const MainSection = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(
theme.components.main.primary.programs.main.default
)};
`}
`;
const MainContent = styled.div<{ noMatch: boolean }>`
${({ theme, noMatch }) => css`
${PgTheme.convertToCSS(
theme.components.main.primary.programs.main.content.default
)};
${noMatch
? "justify-content: center; align-items: center"
: "height: fit-content"};
`}
`;
const NoMatchText = styled(Text)`
${({ theme }) => css`
width: 21rem;
height: 5rem;
font-size: ${theme.font.other.size.small};
`}
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary/Programs/ProgramCard.tsx
|
import { FC } from "react";
import styled, { css } from "styled-components";
import Img from "../../../../components/Img";
import Link from "../../../../components/Link";
import Markdown from "../../../../components/Markdown";
import Tag from "../../../../components/Tag";
import Tooltip from "../../../../components/Tooltip";
import { Github } from "../../../../components/Icons";
import {
Arrayable,
PgTheme,
TutorialData,
TutorialDetailKey,
} from "../../../../utils/pg";
export type ProgramCardProps = {
/** Program name */
name: string;
/** Program description */
description: string;
/** Repository URL */
repo: string;
/**
* Theoratically we should be able to get the icon URL from the repository
* URL e.g. "https://github.com/solana-playground.png", but unfortunately
* github.com doesn't respond with CORS headers so we can't use it with the
* following request headers:
* ```
* "Cross-Origin-Embedder-Policy": "require-corp",
* "Cross-Origin-Opener-Policy": "same-origin"
* ```
*/
icon: string;
} & Required<Pick<TutorialData, "framework" | "categories">>;
const ProgramCard: FC<ProgramCardProps> = ({
name,
description,
repo,
icon,
framework,
categories,
}) => (
<Wrapper>
<Header>
<HeaderLeft>
<Link href={`/${repo}`}>
<ProgramImg src={icon} />
</Link>
<Title href={`/${repo}`}>{name}</Title>
</HeaderLeft>
<HeaderRight>
<Tooltip element="View in GitHub">
<Link href={repo}>
<Github />
</Link>
</Tooltip>
</HeaderRight>
</Header>
<Description>{description}</Description>
<Tags>
<ClickableTag kind="framework" value={framework} />
{categories
.sort((a, b) => a.localeCompare(b))
.map((category) => (
<ClickableTag key={category} kind="categories" value={category} />
))}
</Tags>
</Wrapper>
);
const Wrapper = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(
theme.components.main.primary.programs.main.content.card
)};
`}
`;
const Header = styled.div`
display: flex;
justify-content: space-between;
& > div {
display: flex;
align-items: center;
}
`;
const HeaderLeft = styled.div``;
const HeaderRight = styled.div``;
const ProgramImg = styled(Img)`
${({ theme }) => css`
border-radius: ${theme.default.borderRadius};
width: 2rem;
height: 2rem;
`}
`;
const Title = styled(Link)`
${({ theme }) => css`
font-size: ${theme.font.other.size.medium};
margin-left: 0.75rem;
font-weight: bold;
color: inherit;
`}
`;
const Description = styled(Markdown)`
${({ theme }) => css`
height: 3rem;
color: ${theme.colors.default.textSecondary};
${PgTheme.getClampLinesCSS(2)};
`}
`;
const Tags = styled.div`
display: flex;
gap: 1rem;
`;
interface ClickableTagProps {
kind: TutorialDetailKey;
value: Arrayable<string> | undefined;
}
const ClickableTag: FC<ClickableTagProps> = (props) => (
<Link href={`/programs?${props.kind}=${props.value}`}>
<Tag {...props} />
</Link>
);
export default ProgramCard;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary/Programs/index.ts
|
export { Programs } from "./Programs";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary/Tutorials/filters.ts
|
import {
PgFramework,
PgLanguage,
TutorialLevel,
TUTORIAL_LEVELS,
} from "../../../../utils/pg";
/** All tutorial filters */
export const FILTERS = [
{
param: "level",
filters: TUTORIAL_LEVELS,
sortFn: sortByLevel,
},
{
param: "framework",
filters: PgFramework.all.map((f) => f.name),
},
{
param: "languages",
filters: PgLanguage.all.map((lang) => lang.name),
},
// TODO: Enable once there are more tutorials with various categories
// {
// param: "categories",
// filters: TUTORIAL_CATEGORIES,
// },
] as const;
/** Sort based on `TutorialLevel`. */
export function sortByLevel<T extends { level: TutorialLevel }>(a: T, b: T) {
return TUTORIAL_LEVELS.indexOf(a.level) - TUTORIAL_LEVELS.indexOf(b.level);
}
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary/Tutorials/FeaturedTutorial.tsx
|
import { FC } from "react";
import styled, { css } from "styled-components";
import Button from "../../../../components/Button";
import Img from "../../../../components/Img";
import TutorialDetails from "../../../../components/Tutorial/TutorialDetails";
import { PgTheme, PgTutorial, TutorialData } from "../../../../utils/pg";
interface FeaturedTutorialProps {
tutorial: TutorialData;
}
const FeaturedTutorial: FC<FeaturedTutorialProps> = ({ tutorial }) => (
<Wrapper>
<LeftWrapper>
<Thumbnail src={tutorial.thumbnail} />
</LeftWrapper>
<RightWrapper>
<RightTopWrapper>
<Name>{tutorial.name}</Name>
<Description>{tutorial.description}</Description>
<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 },
]}
/>
</RightTopWrapper>
<RightBottomWrapper>
<Button
onClick={() => PgTutorial.open(tutorial.name)}
kind="primary"
fontWeight="bold"
>
START LEARNING
</Button>
</RightBottomWrapper>
</RightWrapper>
</Wrapper>
);
const Wrapper = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(
theme.components.main.primary.tutorials.main.content.featured
)};
`}
`;
const LeftWrapper = styled.div``;
const Thumbnail = styled(Img)`
width: 100%;
height: 100%;
object-fit: cover;
`;
const RightWrapper = styled.div`
flex: 1;
padding: 1rem;
display: flex;
flex-direction: column;
justify-content: space-between;
overflow: auto;
gap: 1.5rem;
`;
const RightTopWrapper = styled.div`
display: flex;
flex-direction: column;
gap: 1rem;
`;
const Name = styled.h1``;
const Description = styled.div`
${({ theme }) => css`
color: ${theme.colors.default.textSecondary};
`}
`;
const RightBottomWrapper = styled.div`
margin-left: auto;
`;
export default FeaturedTutorial;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary/Tutorials/index.ts
|
export { Tutorials } from "./Tutorials";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary/Tutorials/Tutorials.tsx
|
import styled, { css } from "styled-components";
import FeaturedTutorial from "./FeaturedTutorial";
import TutorialCard from "./TutorialCard";
import FilterGroups from "../../../../components/FilterGroups";
import Link from "../../../../components/Link";
import SearchBar from "../../../../components/SearchBar";
import Text from "../../../../components/Text";
import { FILTERS, sortByLevel } from "./filters";
import { Sad } from "../../../../components/Icons";
import { useFilteredSearch } from "../../../../hooks";
import { GITHUB_URL } from "../../../../constants";
import { PgTheme, PgTutorial } from "../../../../utils/pg";
/**
* Tutorial items sorted by date.
*
* The first 3 tutorials are kept in order because they are essential "Hello
* world" tutorials. The remaining tutorials are sorted from the newest to the
* oldest.
*/
const tutorials = [
...PgTutorial.all.slice(0, 3),
...PgTutorial.all.slice(3).sort(() => -1),
];
export const Tutorials = () => {
const filteredSearch = useFilteredSearch({
route: "/tutorials",
items: tutorials,
filters: FILTERS,
sort: sortByLevel,
});
if (!filteredSearch) return null;
const { featuredItems, regularItems, searchBarProps } = filteredSearch;
return (
<Wrapper>
<TopSection>
<Title>Learn</Title>
<SearchBar
{...searchBarProps}
placeholder="Search tutorials"
searchButton={{ position: "right", width: "2.5rem" }}
/>
</TopSection>
<MainSectionScrollWrapper>
<MainSection>
<SideWrapper>
<FiltersWrapper>
<FilterGroups filters={FILTERS} items={tutorials} />
</FiltersWrapper>
</SideWrapper>
<ContentWrapper>
{!featuredItems.length && !regularItems.length && <NoMatch />}
{featuredItems.length > 0 && (
<FeaturedTutorial tutorial={featuredItems[0]} />
)}
{regularItems.length > 0 && (
<RegularTutorialsWrapper>
{regularItems.map((t) => (
<TutorialCard key={t.name} {...t} />
))}
</RegularTutorialsWrapper>
)}
</ContentWrapper>
</MainSection>
</MainSectionScrollWrapper>
<BottomSection>
<Link href={`${GITHUB_URL}/tree/master/client/src/tutorials`}>
Contribute
</Link>
</BottomSection>
</Wrapper>
);
};
const Wrapper = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(theme.components.main.primary.tutorials.default)};
`}
`;
const TopSection = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(theme.components.main.primary.tutorials.top)};
`}
`;
const Title = styled.h1``;
const MainSectionScrollWrapper = styled.div`
margin: 2rem 2.5rem;
overflow: hidden;
flex-grow: 1;
`;
const MainSection = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(
theme.components.main.primary.tutorials.main.default
)};
`}
`;
const SideWrapper = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(theme.components.main.primary.tutorials.main.side)};
`}
`;
const FiltersWrapper = styled.div`
position: sticky;
top: 0;
`;
const ContentWrapper = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(
theme.components.main.primary.tutorials.main.content.default
)};
`}
`;
const RegularTutorialsWrapper = styled.div`
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
`;
const NoMatch = () => (
<NoMatchWrapper>
<NoMatchText icon={<Sad />}>No match found</NoMatchText>
</NoMatchWrapper>
);
const NoMatchWrapper = styled.div`
flex: 1;
display: flex;
justify-content: center;
align-items: center;
`;
const NoMatchText = styled(Text)`
${({ theme }) => css`
width: 21rem;
height: 5rem;
font-size: ${theme.font.other.size.small};
`}
`;
const BottomSection = styled.div`
display: flex;
justify-content: center;
align-items: center;
width: 100%;
margin-bottom: 2rem;
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary/Tutorials/TutorialCard.tsx
|
import { FC } from "react";
import styled, { css } from "styled-components";
import Img from "../../../../components/Img";
import Tag from "../../../../components/Tag";
import { PgTheme, PgTutorial, TutorialData } from "../../../../utils/pg";
const TutorialCard: FC<TutorialData> = ({
name,
description,
thumbnail,
level,
framework,
}) => (
<GradientWrapper onClick={() => PgTutorial.open(name)}>
<InsideWrapper>
<ImgWrapper>
<TutorialImg src={thumbnail} />
</ImgWrapper>
<InfoWrapper>
<InfoTopSection>
<NameRow>
<Name>{name}</Name>
<Tag kind="level" value={level} />
</NameRow>
<Description>{description}</Description>
</InfoTopSection>
<InfoBottomSection>
{framework && <Tag kind="framework" value={framework} />}
</InfoBottomSection>
</InfoWrapper>
</InsideWrapper>
</GradientWrapper>
);
const GradientWrapper = styled.div`
${({ theme }) => css`
--img-height: 13.5rem;
position: relative;
width: calc(var(--img-height) * 4 / 3);
height: 23rem;
padding: 0.25rem;
transform-style: preserve-3d;
transition: transform ${theme.default.transition.duration.medium}
${theme.default.transition.type};
&::after {
content: "";
position: absolute;
transform: translateZ(-1px);
height: 100%;
width: 100%;
inset: 0;
margin: auto;
border-radius: ${theme.default.borderRadius};
background: linear-gradient(
45deg,
${theme.colors.default.primary},
${theme.colors.default.secondary}
);
opacity: 0;
transition: opacity ${theme.default.transition.duration.medium}
${theme.default.transition.type};
}
&:hover {
cursor: pointer;
transform: translateY(-0.5rem);
& > div {
background: ${theme.colors.state.hover.bg};
}
&::after {
opacity: 1;
}
}
${PgTheme.convertToCSS(
theme.components.main.primary.tutorials.main.content.card.gradient
)};
`}
`;
const InsideWrapper = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(
theme.components.main.primary.tutorials.main.content.card.default
)};
`}
`;
const ImgWrapper = styled.div`
width: 100%;
height: var(--img-height);
`;
const TutorialImg = styled(Img)`
width: 100%;
height: 100%;
object-fit: cover;
`;
const InfoWrapper = styled.div`
width: 100%;
height: calc(100% - var(--img-height));
padding: 1rem 0.75rem;
display: flex;
flex-direction: column;
justify-content: space-between;
`;
const InfoTopSection = styled.div``;
const NameRow = styled.div`
display: flex;
align-items: center;
gap: 0.5rem;
`;
const Name = styled.span`
font-weight: bold;
`;
const Description = styled.div`
${({ theme }) => css`
margin-top: 0.75rem;
color: ${theme.colors.default.textSecondary};
${PgTheme.getClampLinesCSS(2)};
`}
`;
const InfoBottomSection = styled.div``;
export default TutorialCard;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary/EditorWithTabs/EditorWithTabs.tsx
|
import styled from "styled-components";
import { Editor } from "../../../../components/Editor";
import { Tabs } from "../../../../components/Tabs";
export const EditorWithTabs = () => (
<Wrapper>
<Tabs />
<Editor />
</Wrapper>
);
const Wrapper = styled.div`
display: flex;
flex-direction: column;
width: 100%;
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/primary/EditorWithTabs/index.ts
|
export { EditorWithTabs } from "./EditorWithTabs";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/secondary/secondary.ts
|
import { terminal } from "./terminal";
/** All secondary main view pages in order */
export const MAIN_SECONDARY = [terminal];
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/secondary/index.ts
|
export { MAIN_SECONDARY } from "./secondary";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/secondary/create.ts
|
import { CallableJSX, PgCommon, RequiredKey } from "../../../utils/pg";
/** Secondary main view page parameter */
type MainSecondaryPageParam<N extends string> = {
/** Name of the page */
name: N;
/** Title of the page, defaults to `name` */
title?: string;
/** Keybind for the page */
keybind?: string;
/** Actions available for the page */
actions?: Array<{
/** Action name */
name: string;
/** Action keybind */
keybind?: string;
/** Action icon */
icon: JSX.Element;
/** Action processor */
run: () => void;
}>;
/** Lazy loader for the element */
importElement?: () => Promise<{ default: CallableJSX }>;
/** Get whether the page is in focus */
getIsFocused: () => boolean;
/** Focus the page */
focus: () => void;
};
/** Created sidebar page */
type MainSecondaryPage<N extends string> = RequiredKey<
MainSecondaryPageParam<N>,
"title" | "importElement"
>;
/**
* Create a secondary main view page.
*
* @param page secondary main view page
* @returns the page with correct types
*/
export const createMainSecondaryPage = <N extends string>(
page: MainSecondaryPageParam<N>
) => {
page.title ??= page.keybind ? `${page.name} (${page.keybind})` : page.name;
page.importElement ??= () => {
return import(
`./${PgCommon.toKebabFromTitle(page.name.replace("& ", ""))}/Component`
);
};
return page as MainSecondaryPage<N>;
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/secondary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/secondary/terminal/terminal.tsx
|
import { Clear } from "../../../../components/Icons";
import { PgTerminal } from "../../../../utils/pg";
import { createMainSecondaryPage } from "../create";
export const terminal = createMainSecondaryPage({
name: "Terminal",
keybind: "Ctrl+`",
getIsFocused: PgTerminal.isFocused,
focus: PgTerminal.focus,
actions: [
{
name: "Clear",
keybind: "Ctrl+L",
icon: <Clear />,
run: PgTerminal.clear,
},
],
});
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/secondary
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/secondary/terminal/index.ts
|
export { terminal } from "./terminal";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/secondary/terminal
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/secondary/terminal/Component/Terminal.tsx
|
import TerminalComponent from "../../../../../components/Terminal";
import { PgCommandManager } from "../../../../../utils/pg";
const Terminal = () => <TerminalComponent cmdManager={PgCommandManager} />;
export default Terminal;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/secondary/terminal
|
solana_public_repos/solana-playground/solana-playground/client/src/views/main/secondary/terminal/Component/index.ts
|
export { default } from "./Terminal";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom/bottom.ts
|
import { Address } from "./Address";
import { Balance } from "./Balance";
import { RpcEndpoint } from "./RpcEndpoint";
import { Wallet } from "./Wallet";
/** All bottom components in order */
export const BOTTOM = [Wallet, RpcEndpoint, Address, Balance];
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom/index.ts
|
export { BOTTOM } from "./bottom";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom/Balance/Balance.tsx
|
import styled, { css } from "styled-components";
import Tooltip from "../../../components/Tooltip";
import { useBalance } from "../../../hooks";
import { PgTheme } from "../../../utils/pg";
export const Balance = () => {
const { balance } = useBalance();
if (balance === undefined || balance === null) return null;
return (
<>
<Seperator>|</Seperator>
<Tooltip element="Current balance">
<BalanceText>{`${balance} SOL`}</BalanceText>
</Tooltip>
</>
);
};
const Seperator = styled.span`
margin: 0 0.75rem;
`;
const BalanceText = styled.span`
${({ theme }) => css`
${PgTheme.convertToCSS(theme.components.bottom.balance)};
`}
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom/Balance/index.ts
|
export { Balance } from "./Balance";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom/RpcEndpoint/index.ts
|
export { RpcEndpoint } from "./RpcEndpoint";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom/RpcEndpoint/RpcEndpoint.tsx
|
import { useMemo } from "react";
import styled, { css } from "styled-components";
import Tooltip from "../../../components/Tooltip";
import { NETWORKS, NetworkName } from "../../../constants";
import { useConnection, useWallet } from "../../../hooks";
import { PgTheme } from "../../../utils/pg";
export const RpcEndpoint = () => {
const { connection } = useConnection();
const { wallet } = useWallet();
const networkName = useMemo(() => {
return (
NETWORKS.find((n) => n.endpoint === connection.rpcEndpoint)?.name ??
NetworkName.CUSTOM
);
}, [connection.rpcEndpoint]);
if (!wallet) return null;
return (
<>
<Dash>-</Dash>
<Tooltip element={`RPC endpoint (${connection.rpcEndpoint})`}>
<NetworkNameText>{networkName}</NetworkNameText>
</Tooltip>
</>
);
};
const Dash = styled.span`
margin-right: 0.75rem;
`;
const NetworkNameText = styled.span`
${({ theme }) => css`
${PgTheme.convertToCSS(theme.components.bottom.endpoint)};
`}
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom/Address/Address.tsx
|
import styled, { css } from "styled-components";
import Link from "../../../components/Link";
import Tooltip from "../../../components/Tooltip";
import { useBlockExplorer, useWallet } from "../../../hooks";
import { PgTheme } from "../../../utils/pg";
export const Address = () => {
const blockExplorer = useBlockExplorer();
const { wallet } = useWallet();
if (!wallet) return null;
const walletPkStr = wallet.publicKey.toBase58();
return (
<>
<Seperator>|</Seperator>
<Tooltip element="Your address">
<AddressLink href={blockExplorer.getAddressUrl(walletPkStr)}>
{walletPkStr}
</AddressLink>
</Tooltip>
</>
);
};
const Seperator = styled.span`
margin: 0 0.75rem;
`;
const AddressLink = styled(Link)`
${({ theme }) => css`
${PgTheme.convertToCSS(theme.components.bottom.address)};
`}
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom/Address/index.ts
|
export { Address } from "./Address";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom/Wallet/Wallet.tsx
|
import { useCallback } from "react";
import styled, { css } from "styled-components";
import Button from "../../../components/Button";
import Tooltip from "../../../components/Tooltip";
import { useWallet } from "../../../hooks";
import { PgCommand, PgTheme } from "../../../utils/pg";
export const Wallet = () => {
const { wallet } = useWallet();
// Using a callback because this function might be resolved later than the
// mount of this component
const connect = useCallback(() => PgCommand.connect.run(), []);
return (
<Tooltip element="Toggle Playground Wallet">
<ConnectButton
onClick={connect}
kind="transparent"
leftIcon={<WalletStatus isConnected={!!wallet} />}
>
{wallet
? wallet.isPg
? "Connected to Playground Wallet"
: `Connected to ${wallet.name}`
: "Not connected"}
</ConnectButton>
</Tooltip>
);
};
const ConnectButton = styled(Button)`
${({ theme }) => css`
${PgTheme.convertToCSS(theme.components.bottom.connect)};
`}
`;
const WalletStatus = styled.span<{ isConnected: boolean }>`
${({ isConnected, theme }) => css`
&::before {
content: "";
display: block;
width: 0.75rem;
height: 0.75rem;
border-radius: 50%;
margin-right: 0.25rem;
background: ${isConnected
? theme.colors.state.success.color
: theme.colors.state.error.color};
}
`}
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom
|
solana_public_repos/solana-playground/solana-playground/client/src/views/bottom/Wallet/index.ts
|
export { Wallet } from "./Wallet";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/index.ts
|
export { default } from "./IDE";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/IDE.tsx
|
import Panels from "./Panels";
import Global from "./Global";
import Helpers from "./Helpers";
import Delayed from "../../components/Delayed";
import FadeIn from "../../components/FadeIn";
const IDE = () => (
<FadeIn>
<Panels />
<Global />
<Delayed delay={1000}>
<Helpers />
</Delayed>
</FadeIn>
);
export default IDE;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Panels.tsx
|
import styled from "styled-components";
import Bottom from "./Bottom";
import Main from "./Main";
import Side from "./Side";
import Delayed from "../../../components/Delayed";
import ModalBackdrop from "../../../components/ModalBackdrop";
import Toast from "../../../components/Toast";
import Wallet from "../../../components/Wallet";
import { Id } from "../../../constants";
const Panels = () => (
<Wrapper>
<TopWrapper>
<Side />
<Main />
</TopWrapper>
<Bottom />
{/* Add a delay to the mount of the `Wallet` component because some of the
globals used in that component doesn't get initialized in time */}
<Delayed delay={10}>
<Wallet />
</Delayed>
{/* A portal that is *above* the modal backdrop stacking context */}
<PortalAbove id={Id.PORTAL_ABOVE} />
<ModalBackdrop />
{/* A portal that is *below* the modal backdrop stacking context */}
<PortalBelow id={Id.PORTAL_BELOW}>
<Toast />
</PortalBelow>
</Wrapper>
);
const Wrapper = styled.div`
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
position: relative;
overflow: hidden;
`;
const TopWrapper = styled.div`
display: grid;
grid-template-columns: auto 1fr;
overflow: hidden;
width: 100%;
flex: 1;
`;
const PortalAbove = styled.div`
z-index: 4;
`;
const PortalBelow = styled.div`
z-index: 2;
`;
export default Panels;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/index.ts
|
export { default } from "./Panels";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side/Side.tsx
|
import { useState, useRef, useEffect, useMemo } from "react";
import styled, { css } from "styled-components";
import Left from "./Left";
import Right from "./Right";
import { EventName } from "../../../../constants";
import { PgCommon, PgRouter, PgTheme, PgView } from "../../../../utils/pg";
import { useKeybind, useSetStatic } from "../../../../hooks";
const Side = () => {
const [pageName, setPageName] = useState<SidebarPageName>("Explorer");
const oldPageName = useRef(pageName);
useSetStatic(setPageName, EventName.VIEW_SIDEBAR_PAGE_NAME_SET);
const page = useMemo(() => PgView.getSidebarPage(pageName), [pageName]);
useEffect(() => {
PgCommon.createAndDispatchCustomEvent(
EventName.VIEW_ON_DID_CHANGE_SIDEBAR_PAGE,
page
);
}, [page]);
useEffect(() => {
if (page.route && !PgRouter.location.pathname.startsWith(page.route)) {
PgRouter.navigate(page.route);
}
return page.handle?.()?.dispose;
}, [page]);
const [width, setWidth] = useState(320);
const [oldWidth, setOldWidth] = useState(width);
useEffect(() => {
if (width) setOldWidth(width);
}, [width]);
// Handle keybinds
useKeybind(
PgView.sidebar
.filter((p) => p.keybind)
.map((p) => ({
keybind: p.keybind!,
handle: () => {
setPageName((page) => {
const closeCondition = width !== 0 && page === p.name;
setWidth(closeCondition ? 0 : oldWidth);
return p.name;
});
},
})),
[width, oldWidth]
);
return (
<Wrapper>
<Left
pageName={pageName}
setPageName={setPageName}
oldPageName={oldPageName}
width={width}
setWidth={setWidth}
oldWidth={oldWidth}
/>
<Right
page={page}
width={width}
setWidth={setWidth}
oldWidth={oldWidth}
/>
</Wrapper>
);
};
const Wrapper = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(theme.components.sidebar.default)};
`}
`;
export default Side;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side/index.ts
|
export { default } from "./Side";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side/Right/index.ts
|
export { default } from "./Right";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side/Right/Right.tsx
|
import {
FC,
Dispatch,
SetStateAction,
useEffect,
useState,
useCallback,
} from "react";
import styled, { css } from "styled-components";
import ErrorBoundary from "../../../../../components/ErrorBoundary";
import Resizable from "../../../../../components/Resizable";
import { Wormhole } from "../../../../../components/Loading";
import { EventName } from "../../../../../constants";
import {
NullableJSX,
PgTheme,
PgView,
SetState,
SidebarPage,
} from "../../../../../utils/pg";
import { useResize } from "./useResize";
import { useSetStatic } from "../../../../../hooks";
interface DefaultRightProps {
page: SidebarPage;
}
interface RightProps<W = number> extends DefaultRightProps {
width: W;
setWidth: Dispatch<SetStateAction<W>>;
oldWidth: W;
}
const Right: FC<RightProps> = ({ page, width, setWidth, oldWidth }) => {
const { handleResizeStop, windowHeight } = useResize(setWidth);
return (
<Resizable
size={{ width, height: "100%" }}
minHeight="100%"
maxWidth={window.innerWidth * 0.75}
onResizeStop={handleResizeStop}
enable="right"
>
<Wrapper width={width} oldWidth={oldWidth} windowHeight={windowHeight}>
<Title page={page} />
<Content page={page} />
</Wrapper>
</Resizable>
);
};
const Title: FC<DefaultRightProps> = ({ page }) => (
<TitleWrapper>{page.name.toUpperCase()}</TitleWrapper>
);
const Content: FC<DefaultRightProps> = ({ page }) => {
const [el, setEl] = useState<NullableJSX>(null);
const [loadingCount, setLoadingCount] = useState<number>(0);
// There could be multiple processes that change the loading state and the
// overall loading state should only be disabled when all processes complete.
const setLoading = useCallback((set: SetState<boolean>) => {
setLoadingCount((prev) => {
const val = typeof set === "function" ? set(!!prev) : set;
return val ? prev + 1 : prev - 1;
});
}, []);
useSetStatic(setLoading, EventName.VIEW_SIDEBAR_LOADING_SET);
useEffect(() => {
const ids: boolean[] = [];
const { dispose } = PgView.onDidChangeSidebarPage(async (page) => {
setLoading(true);
const currentId = ids.length;
ids[currentId] ??= false;
try {
const { default: PageComponent } = await page.importElement();
if (ids[currentId + 1] === undefined) setEl(<PageComponent />);
} catch (e: any) {
console.log("SIDEBAR ERROR", e.message);
} finally {
setLoading(false);
}
});
return dispose;
}, [setLoading]);
if (loadingCount) return <Loading page={page} />;
return <ErrorBoundary>{el}</ErrorBoundary>;
};
const Wrapper = styled.div<{
windowHeight: number;
width: number;
oldWidth: number;
}>`
${({ theme, width, oldWidth, windowHeight }) => css`
display: flex;
flex-direction: column;
overflow-y: auto;
height: calc(${windowHeight}px - ${theme.components.bottom.default.height});
min-width: ${width ? width : oldWidth}px;
${PgTheme.getScrollbarCSS()};
${PgTheme.convertToCSS(theme.components.sidebar.right.default)};
`}
`;
const TitleWrapper = styled.div`
${({ theme }) => css`
display: flex;
justify-content: center;
align-items: center;
${PgTheme.convertToCSS(theme.components.sidebar.right.title)};
`}
`;
const Loading: FC<DefaultRightProps> = ({ page }) => {
if (page.LoadingElement) return <page.LoadingElement />;
return (
<LoadingWrapper>
<Wormhole />
</LoadingWrapper>
);
};
const LoadingWrapper = styled.div`
margin-top: 2rem;
`;
export default Right;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side/Right/useResize.tsx
|
import {
Dispatch,
SetStateAction,
useCallback,
useEffect,
useState,
} from "react";
import { Id } from "../../../../../constants";
export const useResize = (setWidth: Dispatch<SetStateAction<number>>) => {
const [windowHeight, setWindowHeight] = useState(getWindowHeight);
// Resize the sidebar on window resize event
useEffect(() => {
const handleResize = () => setWindowHeight(getWindowHeight);
handleResize();
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
const handleResizeStop = useCallback(
(e, direction, ref, d) => {
setWidth((w) => {
const newWidth = w + d.width;
if (newWidth < 180) return 0;
return newWidth;
});
},
[setWidth]
);
return { windowHeight, handleResizeStop };
};
const getWindowHeight = () => {
return document.getElementById(Id.ROOT)?.getClientRects()[0]?.height ?? 979;
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side/Left/Settings.tsx
|
import { FC } from "react";
import styled, { css } from "styled-components";
import Tooltip from "../../../../../components/Tooltip";
import { SETTINGS, Setting as SettingType } from "../../../../../settings";
import { PgTheme } from "../../../../../utils/pg";
const Settings = () => (
<Wrapper>
{SETTINGS.map((setting) => (
<Setting key={setting.name} {...setting} />
))}
</Wrapper>
);
const Wrapper = styled.div`
${({ theme }) => css`
min-width: calc(
${theme.components.sidebar.left.default.width} +
${theme.components.sidebar.right.default.initialWidth}
);
max-height: clamp(20rem, 40rem, 80vh);
background: ${theme.components.tooltip.bg};
border: 1px solid ${theme.colors.default.border};
border-radius: ${theme.default.borderRadius};
box-shadow: ${theme.default.boxShadow};
overflow: auto;
${PgTheme.getScrollbarCSS({ width: "0.25rem" })};
`}
`;
const Setting: FC<SettingType> = ({ name, Component, tooltip, isCheckBox }) => (
<SettingWrapper isCheckBox={isCheckBox}>
<Left>
<SettingName>{name}</SettingName>
{tooltip && <Tooltip help bgSecondary {...tooltip} />}
</Left>
<Right>
<Component />
</Right>
</SettingWrapper>
);
const SettingWrapper = styled.div<Pick<SettingType, "isCheckBox">>`
${({ theme, isCheckBox }) => css`
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
max-width: calc(
${theme.components.sidebar.left.default.width} +
${theme.components.sidebar.right.default.initialWidth}
);
padding: 1rem;
&:not(:last-child) {
border-bottom: 1px solid ${theme.colors.default.border};
}
${!isCheckBox &&
`& > div:last-child {
width: 11.5rem;
}`}
`}
`;
const Left = styled.div`
display: flex;
color: ${({ theme }) => theme.colors.default.textSecondary};
font-weight: bold;
& > :nth-child(2) {
margin-left: 0.5rem;
}
`;
const SettingName = styled.span``;
const Right = styled.div`
margin-left: 1rem;
`;
export default Settings;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side/Left/Left.tsx
|
import {
FC,
SetStateAction,
Dispatch,
MutableRefObject,
useEffect,
} from "react";
import styled, { css, useTheme } from "styled-components";
import SidebarButton from "./SidebarButton";
import Settings from "./Settings";
import Link from "../../../../../components/Link";
import Popover from "../../../../../components/Popover";
import { ClassName, GITHUB_URL } from "../../../../../constants";
import { PgCommon, PgTheme, PgView } from "../../../../../utils/pg";
interface LeftProps<P = SidebarPageName, W = number> {
pageName: P;
setPageName: Dispatch<SetStateAction<P>>;
oldPageName: MutableRefObject<P>;
width: W;
setWidth: Dispatch<SetStateAction<W>>;
oldWidth: W;
}
const Left: FC<LeftProps> = ({
pageName,
setPageName,
oldPageName,
width,
setWidth,
oldWidth,
}) => {
useActiveTab({ pageName, oldPageName, width });
const handleSidebarChange = (value: SidebarPageName) => {
setPageName((state) => {
if (!width) setWidth(oldWidth);
else if (state === value) setWidth(0);
return value;
});
};
return (
<Wrapper>
<Icons>
<Top>
{PgView.sidebar.map((page) => (
<SidebarButton
key={page.name}
tooltipEl={PgCommon.getKeybindTextOS(page.title)}
id={getId(page.name)}
src={page.icon}
onClick={() => handleSidebarChange(page.name)}
/>
))}
</Top>
<Bottom>
<Link href={GITHUB_URL}>
<SidebarButton tooltipEl="GitHub" src="/icons/sidebar/github.png" />
</Link>
<Popover popEl={<Settings />} stackingContext="below-modal">
<SidebarButton
tooltipEl="Settings"
src="/icons/sidebar/settings.webp"
/>
</Popover>
</Bottom>
</Icons>
</Wrapper>
);
};
const useActiveTab = <P extends SidebarPageName>({
pageName,
oldPageName,
width,
}: Pick<LeftProps<P>, "pageName" | "oldPageName" | "width">) => {
const theme = useTheme();
useEffect(() => {
const oldEl = document.getElementById(getId(oldPageName.current));
oldEl?.classList.remove(ClassName.ACTIVE);
const current = width !== 0 ? pageName : "Closed";
const newEl = document.getElementById(getId(current));
newEl?.classList.add(ClassName.ACTIVE);
oldPageName.current = pageName;
}, [pageName, oldPageName, width, theme.name]);
};
const getId = (id: string) => "sidebar" + id;
const Wrapper = styled.div`
${({ theme }) => css`
display: flex;
flex-direction: column;
user-select: none;
overflow: hidden;
${PgTheme.convertToCSS(theme.components.sidebar.left.default)};
`}
`;
const Icons = styled.div`
display: flex;
flex-flow: column nowrap;
justify-content: space-between;
align-items: center;
height: 100%;
`;
const Top = styled.div`
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
width: 100%;
`;
const Bottom = styled.div`
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
width: 100%;
`;
export default Left;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side/Left/SidebarButton.tsx
|
import { ComponentPropsWithoutRef, FC, ReactNode } from "react";
import styled, { css } from "styled-components";
import Img from "../../../../../components/Img";
import Tooltip from "../../../../../components/Tooltip";
import { ClassName } from "../../../../../constants";
import { PgTheme } from "../../../../../utils/pg";
interface SidebarButtonProps extends ComponentPropsWithoutRef<"div"> {
src: string;
tooltipEl: ReactNode;
}
const SidebarButton: FC<SidebarButtonProps> = ({
src,
tooltipEl,
...props
}) => (
<Tooltip element={tooltipEl} placement="right" arrow={{ size: 4 }}>
<IconWrapper {...props}>
<Icon src={src} />
</IconWrapper>
</Tooltip>
);
const IconWrapper = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(theme.components.sidebar.left.button.default)};
&.${ClassName.ACTIVE} {
${PgTheme.convertToCSS(theme.components.sidebar.left.button.selected)};
}
&.${ClassName.ACTIVE} img,
&:hover:not(.${ClassName.ACTIVE}) img {
filter: invert(1);
}
`}
`;
const Icon = styled(Img)`
width: 2rem;
height: 2rem;
padding: 0.25rem;
filter: invert(0.5);
`;
export default SidebarButton;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Side/Left/index.ts
|
export { default } from "./Left";
export * from "./Left";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Main/Main.tsx
|
import styled, { css } from "styled-components";
import Primary from "./Primary";
import Secondary from "./Secondary";
import { PgTheme } from "../../../../utils/pg";
const Main = () => (
<Wrapper>
<Primary />
<Secondary />
</Wrapper>
);
const Wrapper = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(theme.components.main.default)};
`}
`;
export default Main;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Main/index.ts
|
export { default } from "./Main";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Main
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Main/Primary/Primary.tsx
|
import { useCallback, useState } from "react";
import styled, { css, keyframes } from "styled-components";
import ErrorBoundary from "../../../../../components/ErrorBoundary";
import { SpinnerWithBg } from "../../../../../components/Loading";
import { EventName } from "../../../../../constants";
import {
CallableJSX,
NullableJSX,
PgCommon,
PgTheme,
SetElementAsync,
} from "../../../../../utils/pg";
import { useGetAndSetStatic } from "../../../../../hooks";
const Primary = () => {
const [el, setEl] = useState<CallableJSX | NullableJSX>(null);
const setElWithTransition = useCallback(async (SetEl: SetElementAsync) => {
setEl(null);
const El = await PgCommon.transition(async () => {
try {
const ElPromise = typeof SetEl === "function" ? SetEl(null) : SetEl;
return await ElPromise;
} catch (e: any) {
console.log("MAIN VIEW ERROR:", e.message);
}
});
if (El) setEl(typeof El === "function" ? <El /> : El);
}, []);
useGetAndSetStatic(
el,
setElWithTransition,
EventName.VIEW_MAIN_PRIMARY_STATIC
);
return (
<Wrapper>
<StyledSpinnerWithBg loading={!el} size="2rem">
<ErrorBoundary>{el}</ErrorBoundary>
</StyledSpinnerWithBg>
</Wrapper>
);
};
const Wrapper = styled.div`
${({ theme }) => css`
${PgTheme.getScrollbarCSS({ allChildren: true })};
${PgTheme.convertToCSS(theme.components.main.primary.default)};
`}
`;
const StyledSpinnerWithBg = styled(SpinnerWithBg)`
${({ theme }) => css`
display: flex;
& > *:last-child {
flex: 1;
overflow: auto;
opacity: 0;
animation: ${fadeInAnimation} ${theme.default.transition.duration.long}
${theme.default.transition.type} forwards;
}
`}
`;
const fadeInAnimation = keyframes`
0% { opacity: 0 }
40% { opacity : 0 }
100% { opacity: 1 }
`;
export default Primary;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Main
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Main/Primary/index.ts
|
export { default } from "./Primary";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Main
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Main/Secondary/Secondary.tsx
|
import {
SetStateAction,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import styled, { css } from "styled-components";
import Button from "../../../../../components/Button";
import ErrorBoundary from "../../../../../components/ErrorBoundary";
import ProgressBar from "../../../../../components/ProgressBar";
import Resizable from "../../../../../components/Resizable";
import { Close, DoubleArrow, Tick } from "../../../../../components/Icons";
import {
NullableJSX,
PgCommon,
// TODO: Remove
PgEditor,
PgTheme,
} from "../../../../../utils/pg";
import { EventName, Id } from "../../../../../constants";
import { useAsyncEffect, useKeybind, useSetStatic } from "../../../../../hooks";
import { MAIN_SECONDARY } from "../../../../../views";
const Secondary = () => {
const [page, setPage] = useState<MainSecondaryPageName>("Terminal");
useSetStatic(setPage, EventName.VIEW_MAIN_SECONDARY_PAGE_SET);
useEffect(() => {
PgCommon.createAndDispatchCustomEvent(
EventName.VIEW_ON_DID_CHANGE_MAIN_SECONDARY_PAGE,
page
);
}, [page]);
const pageInfo = useMemo(() => getPage(page), [page]);
const [el, setEl] = useState<NullableJSX>(null);
useAsyncEffect(async () => {
const { default: PageComponent } = await pageInfo.importElement();
setEl(<PageComponent />);
}, [pageInfo]);
const [height, setHeight] = useState(getDefaultHeight);
const oldHeight = useRef(height);
useEffect(() => {
if (height !== getMinHeight() && height !== getMaxHeight()) {
oldHeight.current = height;
}
}, [height]);
const setCheckedHeight = useCallback((action: SetStateAction<number>) => {
setHeight((h) => {
const height = typeof action === "function" ? action(h) : action;
const minHeight = getMinHeight();
if (height < minHeight) return minHeight;
const maxHeight = getMaxHeight();
if (height > maxHeight) return maxHeight;
return height;
});
}, []);
useSetStatic(setCheckedHeight, EventName.VIEW_MAIN_SECONDARY_HEIGHT_SET);
const handleResizeStop = useCallback(
(_e, _dir, _ref, d) => setCheckedHeight((h) => h + d.height),
[setCheckedHeight]
);
const toggleMinimize = useCallback(() => {
setHeight((h) => {
const minHeight = getMinHeight();
if (h === minHeight) pageInfo.focus();
else PgEditor.focus();
return h === minHeight ? oldHeight.current : minHeight;
});
}, [pageInfo]);
// Combine page actions with default actions
const actions: typeof pageInfo["actions"] = useMemo(
() => [
...(pageInfo.actions ?? []),
{
name: "Toggle Maximize",
keybind: "Ctrl+M",
icon:
height === getMaxHeight() && getMaxHeight() !== getDefaultHeight() ? (
<DoubleArrow rotate="180deg" />
) : (
<DoubleArrow />
),
run: () => {
setHeight((h) => {
const maxHeight = getMaxHeight();
return h === maxHeight ? oldHeight.current : maxHeight;
});
},
},
{
name: "Toggle Minimize",
keybind: "Ctrl+J",
icon: height === getMinHeight() ? <Tick /> : <Close />,
run: toggleMinimize,
},
],
[pageInfo, height, toggleMinimize]
);
// Page keybinds
useKeybind(
MAIN_SECONDARY.filter((p) => p.keybind).map((p) => ({
keybind: p.keybind!,
handle: () => {
setPage(p.name);
const { getIsFocused, focus } = getPage(p.name);
if (getIsFocused()) {
toggleMinimize();
PgEditor.focus();
} else {
if (height === getMinHeight()) toggleMinimize();
focus();
}
},
})),
[height, toggleMinimize]
);
// Action keybinds
useKeybind(
actions
.filter((a) => a.keybind)
.map((a) => ({
keybind: a.keybind!,
handle: a.run,
})),
[actions]
);
return (
<Resizable
size={{ height, width: "100%" }}
minWidth="100%"
minHeight={getMinHeight()}
onResizeStop={handleResizeStop}
enable="top"
>
<Wrapper>
<Topbar>
<TerminalProgress />
<ButtonsWrapper>
{actions.map((action) => (
<Button
key={action.name}
kind="icon"
title={
action.keybind
? `${action.name} (${PgCommon.getKeybindTextOS(
action.keybind
)})`
: action.name
}
onClick={action.run}
>
{action.icon}
</Button>
))}
</ButtonsWrapper>
</Topbar>
<ErrorBoundary>{el}</ErrorBoundary>
</Wrapper>
</Resizable>
);
};
const Wrapper = styled.div`
${({ theme }) => css`
${PgTheme.convertToCSS(theme.components.main.secondary.default)};
& > div:first-child {
height: ${getMinHeight()}px;
}
& > div:last-child {
height: calc(100% - ${getMinHeight()}px);
overflow: hidden;
}
`}
`;
const Topbar = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 1rem;
`;
const TerminalProgress = () => {
const [progress, setProgress] = useState(0);
useSetStatic(setProgress, EventName.TERMINAL_PROGRESS_SET);
return <ProgressBar value={progress} />;
};
const ButtonsWrapper = styled.div`
display: flex;
gap: 0.25rem;
margin-left: 0.5rem;
`;
const getDefaultHeight = () => Math.floor(window.innerHeight / 4);
const getMinHeight = () => 36;
const getMaxHeight = () => {
const bottomHeight = document
.getElementById(Id.BOTTOM)
?.getBoundingClientRect()?.height;
return window.innerHeight - (bottomHeight ?? 0);
};
const getPage = (page: MainSecondaryPageName) => {
return MAIN_SECONDARY.find((p) => p.name === page)!;
};
export default Secondary;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Main
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Main/Secondary/index.ts
|
export { default } from "./Secondary";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Bottom/Bottom.tsx
|
import styled, { css } from "styled-components";
import Delayed from "../../../../components/Delayed";
import ErrorBoundary from "../../../../components/ErrorBoundary";
import Tooltip from "../../../../components/Tooltip";
import { Id } from "../../../../constants";
import { BOTTOM } from "../../../../views";
import { PgTheme } from "../../../../utils/pg";
const Bottom = () => (
<Wrapper id={Id.BOTTOM}>
{/* Add delay to give enough time for component dependencies to initialize */}
<Delayed delay={60}>
{BOTTOM.map((Component, i) => (
<ErrorBoundary
key={i}
Fallback={({ error }) => (
<Tooltip
element={error.message || "Unknown error"}
alwaysTakeFullWidth
>
<FallbackText>
Extension crashed{error.message ? `: ${error.message}` : ""}
</FallbackText>
</Tooltip>
)}
>
<Component />
</ErrorBoundary>
))}
</Delayed>
</Wrapper>
);
const Wrapper = styled.div`
${({ theme }) => css`
& > div {
height: 100%;
display: flex;
align-items: center;
}
${PgTheme.convertToCSS(theme.components.bottom.default)};
`}
`;
const FallbackText = styled.span`
${({ theme }) => css`
display: inline-block;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
max-width: 15rem;
color: ${theme.colors.state.error.color};
`}
`;
export default Bottom;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Panels/Bottom/index.ts
|
export { default } from "./Bottom";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Helpers/index.ts
|
export { default } from "./Helpers";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Helpers/Helpers.tsx
|
import { useHelpConnection } from "./connection";
const Helpers = () => {
useHelpConnection();
return null;
};
export default Helpers;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Helpers
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Helpers/connection/index.ts
|
export { useHelpConnection } from "./useHelpConnection";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Helpers
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Helpers/connection/useHelpConnection.tsx
|
import { useEffect } from "react";
import { Endpoint } from "../../../../constants";
import {
PgCommon,
PgConnection,
PgView,
PgWallet,
SyncOrAsync,
} from "../../../../utils/pg";
/** Show helpers when there is a connection error with the current endpoint. */
export const useHelpConnection = () => {
useEffect(() => {
// Only show each helper once to not be annoying with pop-ups
const cache = {
local: false,
nonLocal: false,
};
const executeOnce = async (
kind: keyof typeof cache,
cb: () => SyncOrAsync
) => {
if (cache[kind]) return;
await cb();
cache[kind] = true;
};
const { dispose } = PgCommon.batchChanges(async () => {
if (cache.local && cache.nonLocal) return;
if (!PgWallet.current) return;
if (PgConnection.current.rpcEndpoint === Endpoint.PLAYNET) return;
const RETRY_AMOUNT = 2;
for (let i = 0; i < RETRY_AMOUNT; i++) {
const isClusterDown = await PgConnection.getIsClusterDown();
if (isClusterDown === false) return;
// Don't sleep on the last iteration
if (i !== RETRY_AMOUNT - 1) await PgCommon.sleep(5000);
}
// Connection failed
if (PgConnection.current.rpcEndpoint === Endpoint.LOCALHOST) {
executeOnce("local", async () => {
const { Local } = await import("./Local");
await PgView.setModal(Local);
});
} else {
executeOnce("nonLocal", async () => {
const { NonLocal } = await import("./NonLocal");
PgView.setToast(NonLocal, {
options: { autoClose: false, closeOnClick: true },
});
});
}
}, [PgConnection.onDidChange, PgWallet.onDidChangeCurrent]);
return dispose;
}, []);
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Helpers/connection
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Helpers/connection/Local/Local.tsx
|
import { useEffect } from "react";
import styled, { css } from "styled-components";
import Foldable from "../../../../../components/Foldable";
import Markdown from "../../../../../components/Markdown";
import Modal from "../../../../../components/Modal";
import Text from "../../../../../components/Text";
import { Info, Sad } from "../../../../../components/Icons";
import { PgCommon, PgConnection, PgView } from "../../../../../utils/pg";
export const Local = () => {
// Check localnet connection
useEffect(() => {
// When this modal shows up, it means there was a connection error to
// localnet but because `PgConnection.isConnected` gets refreshed every
// minute, `PgConnection.isConnected` could still be a truthy value.
//
// TODO: Remove after making change events not fire on mount by default
let initial = true;
const { dispose } = PgConnection.onDidChangeIsConnected((isConnected) => {
// Only close the modal if it's not `initial` and `isConnected` is true
if (!initial && isConnected) PgView.closeModal();
initial = false;
});
return dispose;
}, []);
return (
<Modal title="Connect to localnet">
<Text kind="error" icon={<Sad />}>
Unable to connect to localnet
</Text>
<Content>
<ContentTitle>How to connect</ContentTitle>
<ContentDescription>
Here are the steps for connecting to localnet from playground.
</ContentDescription>
<MarkdownSteps codeFontOnly>
{require("./steps.md")
.replace("<OS_NAME>", PgCommon.getOS() ?? "Other")
.replace(
"<OS_INSTALLATION>",
PgCommon.getOS() === "Windows"
? require("./install-windows.md")
: require("./install-unix.md")
)}
</MarkdownSteps>
<Issues />
</Content>
</Modal>
);
};
const Content = styled.div`
padding: 1rem 0 0.5rem;
`;
const ContentTitle = styled.div`
font-weight: bold;
font-size: ${({ theme }) => theme.font.code.size.large};
`;
const ContentDescription = styled.div`
${({ theme }) => css`
margin-top: 0.5rem;
color: ${theme.colors.default.textSecondary};
font-size: ${theme.font.code.size.small};
`}
`;
const MarkdownSteps = styled(Markdown)`
margin-top: 1.5rem;
`;
const Issues = () => {
const browser = PgCommon.getBrowser();
if (browser === "Firefox") return null;
return (
<Foldable element={<strong>Having issues?</strong>}>
<Text icon={<Info color="info" />}>
<p>
If you have a running test validator, it means your browser is
blocking localhost access and you'll need to enable it in order to
connect.
</p>
{browser === "Brave" && (
<p>
For <strong>Brave Browser</strong>: Click the Brave icon at the
right side of the browser URL bar and drop the shields for this
website.
</p>
)}
</Text>
</Foldable>
);
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Helpers/connection
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Helpers/connection/Local/index.ts
|
export { Local } from "./Local";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Helpers/connection
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Helpers/connection/NonLocal/NonLocal.tsx
|
import { FC, useEffect } from "react";
import styled, { css } from "styled-components";
import Button from "../../../../../components/Button";
import { Endpoint } from "../../../../../constants";
import { PgCommand, PgConnection, PgView } from "../../../../../utils/pg";
import type { ToastChildProps } from "../../../../../components/Toast";
export const NonLocal: FC<ToastChildProps> = ({ id }) => {
// Close the toast if the user changes the cluster
useEffect(() => {
let isInitial = true;
let prevCluster = PgConnection.cluster;
const changeCluster = PgConnection.onDidChangeCluster((cluster) => {
// Only close the toast if it's not initial and it's a different cluster
if (!isInitial && prevCluster !== cluster) PgView.closeToast(id);
isInitial = false;
prevCluster = cluster;
});
const changeIsClusterDown = PgConnection.onDidChangeIsClusterDown(
(isClusterDown) => {
// Anything other than `isClusterDown === false` means either the cluster
// is down, or there is a connection error, which means we don't need to
// close the toast.
if (!isInitial && isClusterDown === false) PgView.closeToast(id);
}
);
return () => {
changeCluster.dispose();
changeIsClusterDown.dispose();
};
}, [id]);
return (
<Wrapper>
<HelpTextWrapper>
<HelpTextTitle>Switch to localnet?</HelpTextTitle>
<HelpTextDescription>
Current endpoint is not responsive.
</HelpTextDescription>
</HelpTextWrapper>
<ButtonsWrapper>
<Button
onClick={() => {
return PgCommand.solana.run(
"config",
"set",
"-u",
Endpoint.LOCALHOST
);
}}
kind="secondary-transparent"
size="small"
>
Yes
</Button>
<Button kind="no-border" size="small">
No
</Button>
</ButtonsWrapper>
</Wrapper>
);
};
const Wrapper = styled.div``;
const HelpTextWrapper = styled.div``;
const HelpTextTitle = styled.div``;
const HelpTextDescription = styled.div`
${({ theme }) => css`
margin-top: 0.25rem;
color: ${theme.colors.default.textSecondary};
font-size: ${theme.font.code.size.small};
`}
`;
const ButtonsWrapper = styled.div`
display: flex;
justify-content: flex-end;
margin-top: 1rem;
& > button {
margin-left: 1rem;
}
`;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Helpers/connection
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Helpers/connection/NonLocal/index.ts
|
export { NonLocal } from "./NonLocal";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide
|
solana_public_repos/solana-playground/solana-playground/client/src/pages/ide/Global/Global.tsx
|
import { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { EventName } from "../../../constants";
import { BLOCK_EXPLORERS } from "../../../block-explorers";
import { COMMANDS } from "../../../commands";
import { FRAMEWORKS } from "../../../frameworks";
import { LANGUAGES } from "../../../languages";
import { ROUTES } from "../../../routes";
import { TUTORIALS } from "../../../tutorials";
import { SIDEBAR } from "../../../views";
import {
Disposable,
PgBlockExplorer,
PgCommandManager,
PgCommon,
PgConnection,
PgExplorer,
PgFramework,
PgGlobal,
PgLanguage,
PgProgramInfo,
PgRouter,
PgTutorial,
PgView,
PgWallet,
} from "../../../utils/pg";
import { useDisposable, useSetStatic } from "../../../hooks";
// Set fields
PgBlockExplorer.all = BLOCK_EXPLORERS;
PgCommandManager.all = COMMANDS;
PgFramework.all = FRAMEWORKS;
PgLanguage.all = LANGUAGES;
PgTutorial.all = TUTORIALS;
PgView.sidebar = SIDEBAR;
const GlobalState = () => {
useDisposable(PgGlobal.init);
useRouter();
useExplorer();
useDisposable(PgConnection.init);
useDisposable(PgBlockExplorer.init); // Must be after `PgConnection` init
useDisposable(PgWallet.init);
useProgramInfo();
return null;
};
/** Initialize `PgProgramInfo` on explorer initialization and workspace switch. */
const useProgramInfo = () => {
useEffect(() => {
let programInfo: Disposable | undefined;
const batch = PgCommon.batchChanges(async () => {
programInfo?.dispose();
programInfo = await PgProgramInfo.init();
}, [PgExplorer.onDidInit, PgExplorer.onDidSwitchWorkspace]);
return () => {
programInfo?.dispose();
batch.dispose();
};
}, []);
};
/** Handle URL routing. */
const useRouter = () => {
// Init
useEffect(() => {
const { dispose } = PgRouter.init(ROUTES);
return dispose;
}, []);
// Location
const location = useLocation();
// Change method
useEffect(() => {
PgCommon.createAndDispatchCustomEvent(
EventName.ROUTER_ON_DID_CHANGE_PATH,
location.pathname
);
}, [location.pathname]);
// Navigate
const navigate = useNavigate();
useSetStatic(navigate, EventName.ROUTER_NAVIGATE);
};
// TODO: Remove and handle this from explorer impl
/** Handle explorer consistency. */
const useExplorer = () => {
// Handle loading state
useEffect(() => {
const { dispose } = PgExplorer.onDidInit(() => {
// Check whether the tab state is valid
// Invalid case: https://github.com/solana-playground/solana-playground/issues/91#issuecomment-1336388179
if (PgExplorer.tabs.length && !PgExplorer.currentFilePath) {
PgExplorer.openFile(PgExplorer.tabs[0]);
}
});
return dispose;
}, []);
};
export default GlobalState;
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.