Skip to content

Commit

Permalink
Refactor components to improve organization
Browse files Browse the repository at this point in the history
  • Loading branch information
arjunkomath committed Jan 11, 2025
1 parent b2a95fd commit 00de119
Show file tree
Hide file tree
Showing 12 changed files with 520 additions and 540 deletions.
15 changes: 8 additions & 7 deletions app/(dashboard)/[tenant]/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import NavBar from "@/components/console/navbar";
import { ReportTimezone } from "@/components/core/report-timezone";
import { isDatabaseReady } from "@/lib/utils/useDatabase";
import { getOrganizations, getOwner } from "@/lib/utils/useOwner";
import { getOwner } from "@/lib/utils/useOwner";
import { redirect } from "next/navigation";

export const fetchCache = "force-no-store"; // disable cache for console pages
Expand All @@ -16,19 +16,20 @@ export default async function ConsoleLayout(props: {
const params = await props.params;

const { children } = props;
const { orgId, orgSlug, userId } = await getOwner();

const ready = await isDatabaseReady();
const { orgId, orgSlug } = await getOwner();
const organizations = await getOrganizations();
const activatedOrg = organizations.find((org) => org.id === orgId) ?? null;
if (params.tenant !== orgSlug) {
redirect("/start");
}

if (!ready || params.tenant !== orgSlug) {
const ready = await isDatabaseReady();
if (!ready) {
redirect("/start");
}

return (
<div className="relative flex min-h-full flex-col">
<NavBar orgs={organizations} activeOrg={activatedOrg} />
<NavBar activeOrgId={orgId ?? userId} activeOrgSlug={orgSlug} />

<div className="mx-auto w-full flex-grow lg:flex">
<div className="min-w-0 flex-1 xl:flex">
Expand Down
19 changes: 19 additions & 0 deletions app/(dashboard)/[tenant]/settings/actions.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
"use server";

import { logtoConfig } from "@/app/logto";
import { user } from "@/drizzle/schema";
import { updateUser } from "@/lib/ops/auth";
import { database } from "@/lib/utils/useDatabase";
import { getOwner } from "@/lib/utils/useOwner";
import { signOut } from "@logto/next/server-actions";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { cookies } from "next/headers";

Expand All @@ -25,5 +30,19 @@ export async function updateUserData(payload: FormData) {
[key]: value,
});
revalidatePath(`/${orgSlug}/settings`);

const db = await database();
if (key === "name") {
const [firstName, lastName] = value.split(" ");
db.update(user)
.set({ firstName, lastName })
.where(eq(user.id, userId))
.run();
}

return { success: true };
}

export async function logout() {
await signOut(logtoConfig);
}
5 changes: 2 additions & 3 deletions components/console/navbar-links.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,10 @@ import { useMemo } from "react";
import logo from "../../public/images/logo.png";
import { createToastWrapper } from "../core/toast";

export default function NavBarLinks() {
export default function NavBarLinks({ orgSlug }: { orgSlug: string }) {
const { systemTheme: theme } = useTheme();
const path = usePathname();
const { projectId } = useParams();
const orgSlug = "personal";

const [isSticky, ref] = useDetectSticky();

Expand Down Expand Up @@ -65,7 +64,7 @@ export default function NavBarLinks() {
current: path.endsWith("/settings"),
},
];
}, [path, projectId]);
}, [path, projectId, orgSlug]);

return (
<>
Expand Down
19 changes: 8 additions & 11 deletions components/console/navbar.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,23 @@
import type { Organization } from "@/lib/ops/auth";
import Image from "next/image";
import Link from "next/link";
import logo from "../../public/images/logo.png";
import { OrgSwitcher, UserButton } from "../core/auth";
import NavBarLinks from "./navbar-links";

export default function NavBar({
orgs,
activeOrg,
activeOrgId,
activeOrgSlug,
}: {
orgs: Organization[];
activeOrg: Organization | null;
activeOrgId: string;
activeOrgSlug: string;
}) {
const orgSlug = "personal";

return (
<>
<nav className="flex-shrink-0 bg-background text-black dark:bg-gray-950 dark:text-white">
<div className="mx-auto px-4 lg:px-8">
<div className="relative flex h-16 items-center justify-between">
<div className="ml-1 flex items-center justify-center">
<Link href={`/${orgSlug}/projects`} prefetch={false}>
<Link href={`/${activeOrgSlug}/projects`} prefetch={false}>
<div className="lg:px-0">
<Image
src={logo}
Expand All @@ -47,17 +44,17 @@ export default function NavBar({
<path d="M16.88 3.549L7.12 20.451" />
</svg>

<OrgSwitcher orgs={orgs} activeOrg={activeOrg} />
<OrgSwitcher activeOrgId={activeOrgId} />
</div>

<div className="ml-2 flex justify-center">
<UserButton orgSlug={orgSlug} />
<UserButton orgSlug={activeOrgSlug} />
</div>
</div>
</div>
</nav>

<NavBarLinks />
<NavBarLinks orgSlug={activeOrgSlug} />
</>
);
}
25 changes: 13 additions & 12 deletions components/core/auth.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { logtoConfig } from "@/app/logto";
"use client";

import { logout } from "@/app/(dashboard)/[tenant]/settings/actions";
import type { Organization } from "@/lib/ops/auth";
import { signOut } from "@logto/next/server-actions";
import { ChevronsUpDown, Plus, User } from "lucide-react";
import Link from "next/link";
import { useMemo, useState } from "react";
import { Button } from "../ui/button";
import {
DropdownMenu,
Expand All @@ -14,12 +16,16 @@ import {
} from "../ui/dropdown-menu";

export const OrgSwitcher = ({
orgs,
activeOrg,
activeOrgId,
}: {
orgs: Organization[];
activeOrg: Organization | null;
activeOrgId: string;
}) => {
const [orgs, setOrgs] = useState<Organization[]>([]);
const activeOrg = useMemo(
() => orgs.find((org) => org.id === activeOrgId),
[orgs, activeOrgId],
);

return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
Expand Down Expand Up @@ -132,12 +138,7 @@ export const UserButton = ({ orgSlug }: { orgSlug: string }) => {
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem>
<form
action={async () => {
"use server";
await signOut(logtoConfig);
}}
>
<form action={logout}>
<button type="submit">Sign Out</button>
</form>
</DropdownMenuItem>
Expand Down
14 changes: 9 additions & 5 deletions components/core/markdown-view.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
"use client";

import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";

export const MarkdownView = ({ content }: { content: string }) => {
return (
<ReactMarkdown className="prose max-w-5xl dark:prose-invert">
{content}
</ReactMarkdown>
);
return (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
className="prose max-w-5xl dark:prose-invert"
>
{content}
</ReactMarkdown>
);
};
1 change: 0 additions & 1 deletion components/project/shared/assigee.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { UserAvatar } from "@/components/core/user-avatar";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import type { User } from "@/drizzle/types";
import { cn } from "@/lib/utils";

Expand Down
2 changes: 0 additions & 2 deletions lib/ops/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,6 @@ export const updateUser = async (
export const getOrganizationsForUser = async (
userId: string,
): Promise<Organization[]> => {
// is this slowing the app?
return [];
const { access_token } = await fetchAccessToken();
if (!access_token) {
throw new Error("Access token not found");
Expand Down
47 changes: 47 additions & 0 deletions lib/utils/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import Database from "better-sqlite3";

export class CacheStore {
#db;

constructor() {
this.#db = this.#openDatabase();
}

#openDatabase() {
const db = new Database("sqlite/cache.db");

db.prepare(`
CREATE TABLE IF NOT EXISTS key_value (
key TEXT NOT NULL PRIMARY KEY,
value,
UNIQUE(key)
);
`).run();

return db;
}

get<T>(key: string) {
const result = this.#db
.prepare("SELECT value FROM key_value WHERE key = ?;")
.get(key);

const value = (result as { value: string })?.value;
if (!value) return undefined;
return JSON.parse(value as string) as T;
}

set(key: string, value: string | number) {
const result = this.#db
.prepare(
"INSERT OR REPLACE INTO key_value (key, value) VALUES (?, ?) RETURNING *;",
)
.run(key, JSON.stringify(value));

return result;
}

delete(key: string) {
this.#db.prepare("DELETE FROM key_value WHERE key = ?;").run(key);
}
}
12 changes: 7 additions & 5 deletions lib/utils/useOwner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,19 +50,21 @@ export async function getOwner(): Promise<Result> {
if (!claims?.sub) {
throw new Error("User not found");
}

const userId = claims.sub;
const organizationIds = claims.organizations ?? [];

const cookieStore = await cookies();

const activeOrgId = cookieStore.get("activeOrgId")?.value;
const activeOrgSlug = cookieStore.get("activeOrgSlug")?.value ?? "personal";
const ownerId = activeOrgId ?? userId;
const activeOrgId = organizationIds.find(
(id) => id === cookieStore.get("activeOrgId")?.value,
);

return {
ownerId,
ownerId: activeOrgId ?? userId,
userId,
orgId: activeOrgId,
orgSlug: activeOrgSlug,
orgSlug: activeOrgId ?? userId,
} as Result;
}

Expand Down
9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"better-sqlite3": "^11.7.0",
"class-variance-authority": "^0.6.1",
"clsx": "^1.2.1",
"cmdk": "^1.0.0",
"cmdk": "0.2.0",
"date-fns": "^2.30.0",
"dayjs": "^1.11.12",
"drizzle-orm": "^0.38.2",
Expand All @@ -52,12 +52,13 @@
"react-dom": "19.0.0",
"react-dropzone": "^14.2.3",
"react-hot-toast": "^2.4.1",
"react-markdown": "^9.0.1",
"react-markdown": "^9.0.3",
"react-simplemde-editor": "^5.2.0",
"remark": "^14.0.3",
"remark": "^15.0.1",
"remark-gfm": "^4.0.0",
"rrule": "^2.8.1",
"sharp": "^0.33.4",
"strip-markdown": "^5.0.1",
"strip-markdown": "^6.0.0",
"svix": "^1.5.2",
"tailwind-merge": "^1.13.2",
"tailwindcss": "3.3.2",
Expand Down
Loading

0 comments on commit 00de119

Please sign in to comment.