Skip to content

Implemented export to GitHub functionality #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions mobile-magic/apps/frontend/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
NEXT_PUBLIC_BACKEND_URL=
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=
CLERK_SECRET_KEY=
NEXT_PUBLIC_GITHUB_CLIENT_ID=
2 changes: 1 addition & 1 deletion mobile-magic/apps/frontend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ yarn-error.log*
.pnpm-debug.log*

# env files (can opt-in for committing if needed)
.env*
.env

# vercel
.vercel
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { useRouter } from "next/navigation"
import Image from "next/image";
import axios from "axios";
import { PreviewIframe } from "@/components/PreviewIframe";
import { GitHubModal } from "@/components/GitHubModal";

export const Project: React.FC<{ projectId: string, sessionUrl: string, previewUrl: string, workerUrl: string }> = ({projectId, sessionUrl, previewUrl, workerUrl }) => {
const router = useRouter()
Expand Down Expand Up @@ -97,6 +98,7 @@ export const Project: React.FC<{ projectId: string, sessionUrl: string, previewU
</div>
<div className="flex-1 min-w-0 overflow-hidden p-4">
<div className="flex items-center justify-end gap-2 pb-2">
<GitHubModal projectId={projectId} workerUrl={workerUrl} />
<Button variant={tab === "code" ? "default" : "outline"} onClick={() => setTab("code")}>Code</Button>
<Button variant={tab === "preview" ? "default" : "outline"} onClick={() => setTab("preview")}>Preview</Button>
<Button variant="outline" onClick={() => setTab("split")}>Split</Button>
Expand Down
13 changes: 13 additions & 0 deletions mobile-magic/apps/frontend/components/GitHubIcon.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export function GitHubIcon() {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
role="img"
viewBox="0 0 24 24"
className="mr-1"
>
<title>GitHub</title>
<path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
</svg>
);
}
298 changes: 298 additions & 0 deletions mobile-magic/apps/frontend/components/GitHubModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,298 @@
import React, { useEffect, useState } from "react";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
import { Copy, ExternalLink } from "lucide-react";
import { GitHubIcon } from "./GitHubIcon";
import axios from "axios";
import { useAuth } from "@clerk/nextjs";
import { useRouter } from "next/navigation";

export const GitHubModal: React.FC<{
projectId: string;
workerUrl: string;
}> = ({ projectId, workerUrl }) => {
const { getToken } = useAuth();
const [isConnected, setIsConnected] = useState(false);
const [isRepoCreated, setIsRepoCreated] = useState(false);
const [repoUrl, setRepoUrl] = useState<string | null>(null);
const [gitHubUsername, setGitHubUsername] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const [copied, setCopied] = useState(false);
const [cloneUrl, setCloneUrl] = useState<string | null>(null);
const branch = "main";

useEffect(() => {
(async () => {
const code = new URLSearchParams(window.location.search).get("code");
if (code) {
setIsLoading(true);
try {
const response = await axios.post(
`${process.env.NEXT_PUBLIC_BACKEND_URL}/github/token`,
{
code,
redirectUri: `${window.location.origin}/project/${projectId}`,
},
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${await getToken()}`,
},
}
);

if (response.status != 200) {
console.log("Error exchanging code to access token");
return;
}
setGitHubUsername(response.data.username);
router.push(`/project/${projectId}`);
} catch (err) {
console.log("GitHub OAuth error:", err);
} finally {
setIsLoading(false);
}
} else {
setIsLoading(true);
try {
const response = await axios.get(
`${process.env.NEXT_PUBLIC_BACKEND_URL}/github/repoUrl?projectId=${projectId}`,
{
headers: {
Authorization: `Bearer ${await getToken()}`,
},
}
);
if (response.status == 200) {
setRepoUrl(response.data.repoUrl);
setCloneUrl(getCloneUrl(response.data.repoUrl, "HTTPS"));
}
} catch (error) {
console.log(error);
} finally {
setIsLoading(false);
}
}
})();
}, []);

useEffect(() => {
setIsRepoCreated(!!repoUrl);
setIsConnected(!!gitHubUsername);
}, [repoUrl, gitHubUsername]);

function copyToClipboard(text: string) {
navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}

async function handleOnConnect() {
setIsLoading(true);
try {
const response = await axios.get(
`${process.env.NEXT_PUBLIC_BACKEND_URL}/github/username`,
{
headers: {
Authorization: `Bearer ${await getToken()}`,
},
}
);
if (response.status == 200) {
if (response.data.isConnected)
setGitHubUsername(response.data.gitHubUsername);
else {
const redirectUri = encodeURIComponent(
`${window.location.origin}/project/${projectId}`
);
const authUrl = `https://github.com/login/oauth/authorize?client_id=${process.env.NEXT_PUBLIC_GITHUB_CLIENT_ID}&redirect_uri=${redirectUri}&scope=repo`;
window.location.href = authUrl;
}
}
} catch (error) {
console.log(error);
} finally {
setIsLoading(false);
}
}

async function handleCreateRepo() {
setIsLoading(true);
try {
const response = await axios.post(
`${process.env.NEXT_PUBLIC_BACKEND_URL}/github/createRepo`,
{
projectId,
workerUrl,
},
{
headers: {
Authorization: `Bearer ${await getToken()}`,
},
}
);
if (response.status == 200) {
setRepoUrl(`${response.data.repoUrl}`);
setCloneUrl(getCloneUrl(response.data.repoUrl, "HTTPS"));
}
} catch (error) {
console.log(error);
} finally {
setIsLoading(false);
}
}

return (
<Popover>
<PopoverTrigger asChild>
<Button className="cursor-pointer font-semibold">
<GitHubIcon />
GitHub
</Button>
</PopoverTrigger>
<PopoverContent className="w-[350px] bg-black text-white border-gray-800 p-4">
{isLoading ? (
<LoadingSpinner />
) : isRepoCreated ? (
<div className="space-y-3">
<div className="font-extrabold text-xl">GitHub</div>
<div>
<p className="text-gray-300">This project is connected to</p>
<p className="font-semibold text-white">
{repoUrl?.split("/").slice(-2).join("/") || ""}.
</p>
<p className="text-gray-300 text-sm">
Mobile Magic will commit changes to the{" "}
<span className="text-white">{branch}</span> branch.
</p>
</div>

<div className="space-y-2">
<h3 className="text-lg font-bold">Clone</h3>
<div className="flex gap-2">
<Button
variant="outline"
className="text-xs py-1 px-2 h-auto bg-transparent text-white font-bold border-gray-700 hover:bg-gray-800 cursor-pointer"
onClick={() =>
setCloneUrl(getCloneUrl(repoUrl || "", "HTTPS"))
}
>
HTTPS
</Button>
<Button
variant="outline"
className="text-xs py-1 px-2 h-auto bg-transparent text-white font-bold border-gray-700 hover:bg-gray-800 cursor-pointer"
onClick={() => setCloneUrl(getCloneUrl(repoUrl || "", "SSH"))}
>
SSH
</Button>
<Button
variant="outline"
className="text-xs py-1 px-2 h-auto bg-transparent text-white font-bold border-gray-700 hover:bg-gray-800 cursor-pointer"
onClick={() => setCloneUrl(getCloneUrl(repoUrl || "", "CLI"))}
>
CLI
</Button>
</div>

<div className="flex mt-2">
<div className="flex-1 bg-transparent border border-gray-700 rounded-l-md p-2 text-white font-semibold text-xs overflow-x-auto whitespace-nowrap">
{cloneUrl}
</div>
<div className="relative">
<Button
variant="outline"
className="bg-transparent border border-l-0 border-gray-700 rounded-l-none p-1 h-full cursor-pointer"
onClick={() => copyToClipboard(cloneUrl || "")}
>
<Copy className="h-4 w-4 text-blue-400" />
</Button>
{copied && (
<div className="absolute -top-8 left-1/2 transform -translate-x-1/2 text-xs text-white bg-gray-700 px-2 py-1 rounded shadow-md z-10">
Copied
</div>
)}
</div>
</div>
</div>

<div className="space-y-2">
<Button
asChild
variant="outline"
className="w-full bg-transparent border-gray-700 hover:bg-blue-700 text-white text-sm p-2 h-auto font-bold"
>
<a
href={repoUrl?.replace(".com", ".dev") || ""}
target="_blank"
>
Edit in VS Code <ExternalLink className="h-3 w-3 ml-2" />
</a>
</Button>
<Button
asChild
variant="outline"
className="w-full bg-transparent border-gray-700 hover:bg-blue-700 text-white text-sm p-2 h-auto font-bold"
>
<a href={repoUrl || ""} target="_blank">
View on GitHub <ExternalLink className="h-3 w-3 ml-2" />
</a>
</Button>
</div>
</div>
) : isConnected ? (
<div className="space-y-4">
<div className="font-extrabold text-xl">GitHub</div>
<p className="text-gray-300 text-sm">
Connect your project to GitHub to save your code and collaborate
with others.
</p>
<div className="font-bold">Create in</div>
<Button
className="w-full cursor-pointer font-extrabold"
onClick={handleCreateRepo}
>
{gitHubUsername}
</Button>
</div>
) : (
<div className="space-y-4">
<div className="font-extrabold text-xl">GitHub</div>
<p className="text-gray-300 text-sm">
Connect your project to GitHub to save your code and collaborate
with others.
</p>
<Button
className="cursor-pointer font-extrabold"
onClick={handleOnConnect}
>
<GitHubIcon />
Connect GitHub
</Button>
</div>
)}
</PopoverContent>
</Popover>
);
};

function LoadingSpinner() {
return (
<div className="flex justify-center items-center py-10">
<div className="animate-spin rounded-full h-10 w-10 border-b-2 border-gray-500"></div>
</div>
);
}

function getCloneUrl(repoUrl: string, type: "HTTPS" | "SSH" | "CLI"): string {
const usernameRepoName = repoUrl.split("/").slice(-2).join("/");
if (type == "HTTPS") return `${repoUrl}.git`;
else if (type == "SSH") return `[email protected]:${usernameRepoName}.git`;
else return `gh repo clone ${usernameRepoName}`;
}
// bg-blue-600 hover:bg-blue-700
48 changes: 48 additions & 0 deletions mobile-magic/apps/frontend/components/ui/popover.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"use client"

import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"

import { cn } from "@/lib/utils"

function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}

function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}

function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 rounded-md border p-4 shadow-md outline-hidden",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}

function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}

export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
Loading