feat: react zitadel
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
import { getEnvironmentVariable } from "@platform/config/environment.ts";
|
import { getEnvironmentVariable } from "@platform/config";
|
||||||
import z from "zod";
|
import z from "zod";
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@modules/identity": "workspace:*",
|
"@modules/identity": "workspace:*",
|
||||||
"@module/workspace": "workspace:*",
|
"@module/workspace": "workspace:*",
|
||||||
"zod": "4.1.11"
|
"@platform/config": "workspace:*",
|
||||||
|
"zod": "4.1.12"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
import identity from "@modules/identity/server.ts";
|
|
||||||
import workspace from "@modules/workspace/server.ts";
|
|
||||||
import { logger } from "@platform/logger";
|
import { logger } from "@platform/logger";
|
||||||
import { context } from "@platform/relay";
|
import { context } from "@platform/relay";
|
||||||
import { Api } from "@platform/server/api.ts";
|
import { Api } from "@platform/server/api.ts";
|
||||||
@@ -26,7 +24,7 @@ await session.bootstrap();
|
|||||||
|
|
||||||
// ### Modules
|
// ### Modules
|
||||||
|
|
||||||
await workspace.bootstrap();
|
// await workspace.bootstrap();
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|--------------------------------------------------------------------------------
|
|--------------------------------------------------------------------------------
|
||||||
@@ -34,7 +32,9 @@ await workspace.bootstrap();
|
|||||||
|--------------------------------------------------------------------------------
|
|--------------------------------------------------------------------------------
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const api = new Api([...identity.routes, ...workspace.routes]);
|
const api = new Api([
|
||||||
|
/*...identity.routes, ...workspace.routes*/
|
||||||
|
]);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|--------------------------------------------------------------------------------
|
|--------------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
import { identity } from "@modules/iam/client.ts";
|
|
||||||
import { getPrincipalSession } from "@modules/identity/server.ts";
|
|
||||||
import { context, UnauthorizedError } from "@platform/relay";
|
import { context, UnauthorizedError } from "@platform/relay";
|
||||||
import { storage } from "@platform/storage";
|
import { storage } from "@platform/storage";
|
||||||
|
|
||||||
|
|||||||
22
apps/react/components.json
Normal file
22
apps/react/components.json
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://ui.shadcn.com/schema.json",
|
||||||
|
"style": "new-york",
|
||||||
|
"rsc": false,
|
||||||
|
"tsx": true,
|
||||||
|
"tailwind": {
|
||||||
|
"config": "tailwind.config.js",
|
||||||
|
"css": "src/index.css",
|
||||||
|
"baseColor": "neutral",
|
||||||
|
"cssVariables": true,
|
||||||
|
"prefix": ""
|
||||||
|
},
|
||||||
|
"iconLibrary": "lucide",
|
||||||
|
"aliases": {
|
||||||
|
"components": "@/components",
|
||||||
|
"utils": "@/libraries/utils",
|
||||||
|
"ui": "@/components/ui",
|
||||||
|
"lib": "@/libraries",
|
||||||
|
"hooks": "@/hooks"
|
||||||
|
},
|
||||||
|
"registries": {}
|
||||||
|
}
|
||||||
@@ -10,17 +10,33 @@
|
|||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@module/account": "workspace:*",
|
||||||
"@platform/relay": "workspace:*",
|
"@platform/relay": "workspace:*",
|
||||||
"@platform/spec": "workspace:*",
|
"@platform/spec": "workspace:*",
|
||||||
|
"@radix-ui/react-avatar": "^1.1.11",
|
||||||
|
"@radix-ui/react-dialog": "^1.1.15",
|
||||||
|
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||||
|
"@radix-ui/react-scroll-area": "^1.2.10",
|
||||||
|
"@radix-ui/react-separator": "^1.1.8",
|
||||||
|
"@radix-ui/react-slot": "^1.2.4",
|
||||||
|
"@radix-ui/react-tooltip": "^1.2.8",
|
||||||
|
"@tabler/icons-react": "3.35.0",
|
||||||
"@tanstack/react-query": "5.89.0",
|
"@tanstack/react-query": "5.89.0",
|
||||||
"@tanstack/react-router": "1.131.47",
|
"@tanstack/react-router": "1.131.47",
|
||||||
"@valkyr/db": "npm:@jsr/valkyr__db@2.0.0",
|
"@valkyr/db": "npm:@jsr/valkyr__db@2.0.0",
|
||||||
"@valkyr/event-emitter": "npm:@jsr/valkyr__event-emitter@1.0.1",
|
"@valkyr/event-emitter": "npm:@jsr/valkyr__event-emitter@1.0.1",
|
||||||
|
"@zitadel/react": "1.1.0",
|
||||||
|
"class-variance-authority": "^0.7.1",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
"fast-equals": "5.2.2",
|
"fast-equals": "5.2.2",
|
||||||
|
"lucide-react": "^0.554.0",
|
||||||
"react": "19.1.1",
|
"react": "19.1.1",
|
||||||
"react-dom": "19.1.1",
|
"react-dom": "19.1.1",
|
||||||
|
"tailwind-merge": "^3.4.0",
|
||||||
"tailwindcss": "4.1.13",
|
"tailwindcss": "4.1.13",
|
||||||
"zod": "4.1.11"
|
"tailwindcss-animate": "^1.0.7",
|
||||||
|
"tw-animate-css": "1.4.0",
|
||||||
|
"zod": "4.1.12"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "9.35.0",
|
"@eslint/js": "9.35.0",
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
import { makeControllerView } from "../libraries/view.ts";
|
|
||||||
import { SessionController } from "./session.controller.ts";
|
|
||||||
|
|
||||||
export const Session = makeControllerView(SessionController, ({ state: { error } }) => {
|
|
||||||
if (error !== undefined) {
|
|
||||||
return "Failed to fetch session";
|
|
||||||
}
|
|
||||||
return <div>Session OK!</div>;
|
|
||||||
});
|
|
||||||
178
apps/react/src/components/app-sidebar.tsx
Normal file
178
apps/react/src/components/app-sidebar.tsx
Normal file
@@ -0,0 +1,178 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
IconCamera,
|
||||||
|
IconChartBar,
|
||||||
|
IconDashboard,
|
||||||
|
IconDatabase,
|
||||||
|
IconFileAi,
|
||||||
|
IconFileDescription,
|
||||||
|
IconFileWord,
|
||||||
|
IconFolder,
|
||||||
|
IconHelp,
|
||||||
|
IconInnerShadowTop,
|
||||||
|
IconListDetails,
|
||||||
|
IconReport,
|
||||||
|
IconSearch,
|
||||||
|
IconSettings,
|
||||||
|
IconUsers,
|
||||||
|
} from "@tabler/icons-react";
|
||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import { NavDocuments } from "@/components/nav-documents";
|
||||||
|
import { NavMain } from "@/components/nav-main";
|
||||||
|
import { NavSecondary } from "@/components/nav-secondary";
|
||||||
|
import { NavUser } from "@/components/nav-user";
|
||||||
|
import {
|
||||||
|
Sidebar,
|
||||||
|
SidebarContent,
|
||||||
|
SidebarFooter,
|
||||||
|
SidebarHeader,
|
||||||
|
SidebarMenu,
|
||||||
|
SidebarMenuButton,
|
||||||
|
SidebarMenuItem,
|
||||||
|
} from "@/components/ui/sidebar";
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
user: {
|
||||||
|
name: "shadcn",
|
||||||
|
email: "m@example.com",
|
||||||
|
avatar: "/avatars/shadcn.jpg",
|
||||||
|
},
|
||||||
|
navMain: [
|
||||||
|
{
|
||||||
|
title: "Dashboard",
|
||||||
|
url: "#",
|
||||||
|
icon: IconDashboard,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Lifecycle",
|
||||||
|
url: "#",
|
||||||
|
icon: IconListDetails,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Analytics",
|
||||||
|
url: "#",
|
||||||
|
icon: IconChartBar,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Projects",
|
||||||
|
url: "#",
|
||||||
|
icon: IconFolder,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Team",
|
||||||
|
url: "#",
|
||||||
|
icon: IconUsers,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
navClouds: [
|
||||||
|
{
|
||||||
|
title: "Capture",
|
||||||
|
icon: IconCamera,
|
||||||
|
isActive: true,
|
||||||
|
url: "#",
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: "Active Proposals",
|
||||||
|
url: "#",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Archived",
|
||||||
|
url: "#",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Proposal",
|
||||||
|
icon: IconFileDescription,
|
||||||
|
url: "#",
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: "Active Proposals",
|
||||||
|
url: "#",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Archived",
|
||||||
|
url: "#",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Prompts",
|
||||||
|
icon: IconFileAi,
|
||||||
|
url: "#",
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: "Active Proposals",
|
||||||
|
url: "#",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Archived",
|
||||||
|
url: "#",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
navSecondary: [
|
||||||
|
{
|
||||||
|
title: "Settings",
|
||||||
|
url: "#",
|
||||||
|
icon: IconSettings,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Get Help",
|
||||||
|
url: "#",
|
||||||
|
icon: IconHelp,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Search",
|
||||||
|
url: "#",
|
||||||
|
icon: IconSearch,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
documents: [
|
||||||
|
{
|
||||||
|
name: "Data Library",
|
||||||
|
url: "#",
|
||||||
|
icon: IconDatabase,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Reports",
|
||||||
|
url: "#",
|
||||||
|
icon: IconReport,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Word Assistant",
|
||||||
|
url: "#",
|
||||||
|
icon: IconFileWord,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
|
||||||
|
return (
|
||||||
|
<Sidebar collapsible="offcanvas" {...props}>
|
||||||
|
<SidebarHeader>
|
||||||
|
<SidebarMenu>
|
||||||
|
<SidebarMenuItem>
|
||||||
|
<SidebarMenuButton asChild className="data-[slot=sidebar-menu-button]:!p-1.5">
|
||||||
|
<a href="#">
|
||||||
|
<IconInnerShadowTop className="!size-5" />
|
||||||
|
<span className="text-base font-semibold">Acme Inc.</span>
|
||||||
|
</a>
|
||||||
|
</SidebarMenuButton>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
</SidebarMenu>
|
||||||
|
</SidebarHeader>
|
||||||
|
<SidebarContent>
|
||||||
|
<NavMain items={data.navMain} />
|
||||||
|
<NavDocuments items={data.documents} />
|
||||||
|
<NavSecondary items={data.navSecondary} className="mt-auto" />
|
||||||
|
</SidebarContent>
|
||||||
|
<SidebarFooter>
|
||||||
|
<NavUser />
|
||||||
|
</SidebarFooter>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
83
apps/react/src/components/nav-documents.tsx
Normal file
83
apps/react/src/components/nav-documents.tsx
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { type Icon, IconDots, IconFolder, IconShare3, IconTrash } from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import {
|
||||||
|
SidebarGroup,
|
||||||
|
SidebarGroupLabel,
|
||||||
|
SidebarMenu,
|
||||||
|
SidebarMenuAction,
|
||||||
|
SidebarMenuButton,
|
||||||
|
SidebarMenuItem,
|
||||||
|
useSidebar,
|
||||||
|
} from "@/components/ui/sidebar";
|
||||||
|
|
||||||
|
export function NavDocuments({
|
||||||
|
items,
|
||||||
|
}: {
|
||||||
|
items: {
|
||||||
|
name: string;
|
||||||
|
url: string;
|
||||||
|
icon: Icon;
|
||||||
|
}[];
|
||||||
|
}) {
|
||||||
|
const { isMobile } = useSidebar();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SidebarGroup className="group-data-[collapsible=icon]:hidden">
|
||||||
|
<SidebarGroupLabel>Documents</SidebarGroupLabel>
|
||||||
|
<SidebarMenu>
|
||||||
|
{items.map((item) => (
|
||||||
|
<SidebarMenuItem key={item.name}>
|
||||||
|
<SidebarMenuButton asChild>
|
||||||
|
<a href={item.url}>
|
||||||
|
<item.icon />
|
||||||
|
<span>{item.name}</span>
|
||||||
|
</a>
|
||||||
|
</SidebarMenuButton>
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<SidebarMenuAction showOnHover className="data-[state=open]:bg-accent rounded-sm">
|
||||||
|
<IconDots />
|
||||||
|
<span className="sr-only">More</span>
|
||||||
|
</SidebarMenuAction>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent
|
||||||
|
className="w-24 rounded-lg"
|
||||||
|
side={isMobile ? "bottom" : "right"}
|
||||||
|
align={isMobile ? "end" : "start"}
|
||||||
|
>
|
||||||
|
<DropdownMenuItem>
|
||||||
|
<IconFolder />
|
||||||
|
<span>Open</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem>
|
||||||
|
<IconShare3 />
|
||||||
|
<span>Share</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem variant="destructive">
|
||||||
|
<IconTrash />
|
||||||
|
<span>Delete</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
))}
|
||||||
|
<SidebarMenuItem>
|
||||||
|
<SidebarMenuButton className="text-sidebar-foreground/70">
|
||||||
|
<IconDots className="text-sidebar-foreground/70" />
|
||||||
|
<span>More</span>
|
||||||
|
</SidebarMenuButton>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
</SidebarMenu>
|
||||||
|
</SidebarGroup>
|
||||||
|
);
|
||||||
|
}
|
||||||
54
apps/react/src/components/nav-main.tsx
Normal file
54
apps/react/src/components/nav-main.tsx
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { type Icon, IconCirclePlusFilled, IconMail } from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
SidebarGroup,
|
||||||
|
SidebarGroupContent,
|
||||||
|
SidebarMenu,
|
||||||
|
SidebarMenuButton,
|
||||||
|
SidebarMenuItem,
|
||||||
|
} from "@/components/ui/sidebar";
|
||||||
|
|
||||||
|
export function NavMain({
|
||||||
|
items,
|
||||||
|
}: {
|
||||||
|
items: {
|
||||||
|
title: string;
|
||||||
|
url: string;
|
||||||
|
icon?: Icon;
|
||||||
|
}[];
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<SidebarGroup>
|
||||||
|
<SidebarGroupContent className="flex flex-col gap-2">
|
||||||
|
<SidebarMenu>
|
||||||
|
<SidebarMenuItem className="flex items-center gap-2">
|
||||||
|
<SidebarMenuButton
|
||||||
|
tooltip="Quick Create"
|
||||||
|
className="bg-primary text-primary-foreground hover:bg-primary/90 hover:text-primary-foreground active:bg-primary/90 active:text-primary-foreground min-w-8 duration-200 ease-linear"
|
||||||
|
>
|
||||||
|
<IconCirclePlusFilled />
|
||||||
|
<span>Quick Create</span>
|
||||||
|
</SidebarMenuButton>
|
||||||
|
<Button size="icon" className="size-8 group-data-[collapsible=icon]:opacity-0" variant="outline">
|
||||||
|
<IconMail />
|
||||||
|
<span className="sr-only">Inbox</span>
|
||||||
|
</Button>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
</SidebarMenu>
|
||||||
|
<SidebarMenu>
|
||||||
|
{items.map((item) => (
|
||||||
|
<SidebarMenuItem key={item.title}>
|
||||||
|
<SidebarMenuButton tooltip={item.title}>
|
||||||
|
{item.icon && <item.icon />}
|
||||||
|
<span>{item.title}</span>
|
||||||
|
</SidebarMenuButton>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
))}
|
||||||
|
</SidebarMenu>
|
||||||
|
</SidebarGroupContent>
|
||||||
|
</SidebarGroup>
|
||||||
|
);
|
||||||
|
}
|
||||||
42
apps/react/src/components/nav-secondary.tsx
Normal file
42
apps/react/src/components/nav-secondary.tsx
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { Icon } from "@tabler/icons-react";
|
||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import {
|
||||||
|
SidebarGroup,
|
||||||
|
SidebarGroupContent,
|
||||||
|
SidebarMenu,
|
||||||
|
SidebarMenuButton,
|
||||||
|
SidebarMenuItem,
|
||||||
|
} from "@/components/ui/sidebar";
|
||||||
|
|
||||||
|
export function NavSecondary({
|
||||||
|
items,
|
||||||
|
...props
|
||||||
|
}: {
|
||||||
|
items: {
|
||||||
|
title: string;
|
||||||
|
url: string;
|
||||||
|
icon: Icon;
|
||||||
|
}[];
|
||||||
|
} & React.ComponentPropsWithoutRef<typeof SidebarGroup>) {
|
||||||
|
return (
|
||||||
|
<SidebarGroup {...props}>
|
||||||
|
<SidebarGroupContent>
|
||||||
|
<SidebarMenu>
|
||||||
|
{items.map((item) => (
|
||||||
|
<SidebarMenuItem key={item.title}>
|
||||||
|
<SidebarMenuButton asChild>
|
||||||
|
<a href={item.url}>
|
||||||
|
<item.icon />
|
||||||
|
<span>{item.title}</span>
|
||||||
|
</a>
|
||||||
|
</SidebarMenuButton>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
))}
|
||||||
|
</SidebarMenu>
|
||||||
|
</SidebarGroupContent>
|
||||||
|
</SidebarGroup>
|
||||||
|
);
|
||||||
|
}
|
||||||
51
apps/react/src/components/nav-user.controller.ts
Normal file
51
apps/react/src/components/nav-user.controller.ts
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import { Controller } from "../libraries/controller.ts";
|
||||||
|
import { type User as ZitadelUser, zitadel } from "../services/zitadel.ts";
|
||||||
|
|
||||||
|
export class NavUserController extends Controller<{
|
||||||
|
user?: User;
|
||||||
|
}> {
|
||||||
|
async onInit() {
|
||||||
|
return {
|
||||||
|
user: await this.#getAuthenticatedUser(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async #getAuthenticatedUser(): Promise<User | undefined> {
|
||||||
|
const user = await zitadel.userManager.getUser();
|
||||||
|
if (user !== null) {
|
||||||
|
return getUserProfile(user);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
authorize() {
|
||||||
|
zitadel.authorize();
|
||||||
|
}
|
||||||
|
|
||||||
|
signout() {
|
||||||
|
zitadel.signout();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getUserProfile({ profile }: ZitadelUser): User {
|
||||||
|
const user: User = { name: "Unknown", email: "unknown@acme.none", avatar: "" };
|
||||||
|
if (profile.name) {
|
||||||
|
user.name = profile.name;
|
||||||
|
} else if (profile.given_name && profile.family_name) {
|
||||||
|
user.name = `${profile.given_name} ${profile.family_name}`;
|
||||||
|
} else if (profile.given_name) {
|
||||||
|
user.name = profile.given_name;
|
||||||
|
}
|
||||||
|
if (profile.email) {
|
||||||
|
user.email = profile.email;
|
||||||
|
}
|
||||||
|
if (profile.picture !== undefined) {
|
||||||
|
user.avatar = profile.picture;
|
||||||
|
}
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
type User = {
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
avatar: string;
|
||||||
|
};
|
||||||
140
apps/react/src/components/nav-user.tsx
Normal file
140
apps/react/src/components/nav-user.tsx
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { IconCreditCard, IconDotsVertical, IconLogout, IconNotification, IconUserCircle } from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuGroup,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar } from "@/components/ui/sidebar";
|
||||||
|
import { useController } from "@/libraries/controller.ts";
|
||||||
|
|
||||||
|
import { NavUserController } from "./nav-user.controller.ts";
|
||||||
|
|
||||||
|
export function NavUser() {
|
||||||
|
const [{ user }, loading, { authorize, signout }] = useController(NavUserController);
|
||||||
|
const { isMobile } = useSidebar();
|
||||||
|
|
||||||
|
console.log({authorize})
|
||||||
|
|
||||||
|
if (loading === true || user === undefined) {
|
||||||
|
return (
|
||||||
|
<SidebarMenu>
|
||||||
|
<SidebarMenuItem>
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<SidebarMenuButton
|
||||||
|
size="lg"
|
||||||
|
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
|
||||||
|
>
|
||||||
|
<Avatar className="h-8 w-8 rounded-lg grayscale">
|
||||||
|
<AvatarImage src="" alt="" />
|
||||||
|
<AvatarFallback className="rounded-lg">CN</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||||
|
<span className="truncate font-medium">Guest</span>
|
||||||
|
<span className="text-muted-foreground truncate text-xs">guest@fixture.none</span>
|
||||||
|
</div>
|
||||||
|
<IconDotsVertical className="ml-auto size-4" />
|
||||||
|
</SidebarMenuButton>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent
|
||||||
|
className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
|
||||||
|
side={isMobile ? "bottom" : "right"}
|
||||||
|
align="end"
|
||||||
|
sideOffset={4}
|
||||||
|
>
|
||||||
|
<DropdownMenuLabel className="p-0 font-normal">
|
||||||
|
<div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
|
||||||
|
<Avatar className="h-8 w-8 rounded-lg">
|
||||||
|
<AvatarImage src="" alt="Guest" />
|
||||||
|
<AvatarFallback className="rounded-lg">CN</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||||
|
<span className="truncate font-medium">Guest</span>
|
||||||
|
<span className="text-muted-foreground truncate text-xs">guest@fixture.none</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</DropdownMenuLabel>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem onClick={() => authorize()}>
|
||||||
|
<IconLogout />
|
||||||
|
Sign in
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
</SidebarMenu>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SidebarMenu>
|
||||||
|
<SidebarMenuItem>
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<SidebarMenuButton
|
||||||
|
size="lg"
|
||||||
|
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
|
||||||
|
>
|
||||||
|
<Avatar className="h-8 w-8 rounded-lg grayscale">
|
||||||
|
<AvatarImage src={user.avatar} alt={user.name} />
|
||||||
|
<AvatarFallback className="rounded-lg">CN</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||||
|
<span className="truncate font-medium">{user.name}</span>
|
||||||
|
<span className="text-muted-foreground truncate text-xs">{user.email}</span>
|
||||||
|
</div>
|
||||||
|
<IconDotsVertical className="ml-auto size-4" />
|
||||||
|
</SidebarMenuButton>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent
|
||||||
|
className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
|
||||||
|
side={isMobile ? "bottom" : "right"}
|
||||||
|
align="end"
|
||||||
|
sideOffset={4}
|
||||||
|
>
|
||||||
|
<DropdownMenuLabel className="p-0 font-normal">
|
||||||
|
<div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
|
||||||
|
<Avatar className="h-8 w-8 rounded-lg">
|
||||||
|
<AvatarImage src={user.avatar} alt={user.name} />
|
||||||
|
<AvatarFallback className="rounded-lg">CN</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||||
|
<span className="truncate font-medium">{user.name}</span>
|
||||||
|
<span className="text-muted-foreground truncate text-xs">{user.email}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</DropdownMenuLabel>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuGroup>
|
||||||
|
<DropdownMenuItem>
|
||||||
|
<IconUserCircle />
|
||||||
|
Account
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem>
|
||||||
|
<IconCreditCard />
|
||||||
|
Billing
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem>
|
||||||
|
<IconNotification />
|
||||||
|
Notifications
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuGroup>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem onClick={() => signout()}>
|
||||||
|
<IconLogout />
|
||||||
|
Log out
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
</SidebarMenu>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
import { Controller } from "../libraries/controller.ts";
|
|
||||||
import { api } from "../services/api.ts";
|
|
||||||
|
|
||||||
export class SessionController extends Controller<{
|
|
||||||
error?: string;
|
|
||||||
}> {
|
|
||||||
async onInit() {
|
|
||||||
await this.getSessionCookie();
|
|
||||||
}
|
|
||||||
|
|
||||||
async getSessionCookie() {
|
|
||||||
const response = await api.auth.authenticate({
|
|
||||||
body: {
|
|
||||||
type: "email",
|
|
||||||
email: "john.doe@fixture.none",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
if ("error" in response) {
|
|
||||||
this.setState("error", undefined);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
27
apps/react/src/components/site-header.tsx
Normal file
27
apps/react/src/components/site-header.tsx
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Separator } from "@/components/ui/separator";
|
||||||
|
import { SidebarTrigger } from "@/components/ui/sidebar";
|
||||||
|
|
||||||
|
export function SiteHeader() {
|
||||||
|
return (
|
||||||
|
<header className="flex h-(--header-height) shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-(--header-height)">
|
||||||
|
<div className="flex w-full items-center gap-1 px-4 lg:gap-2 lg:px-6">
|
||||||
|
<SidebarTrigger className="-ml-1" />
|
||||||
|
<Separator orientation="vertical" className="mx-2 data-[orientation=vertical]:h-4" />
|
||||||
|
<h1 className="text-base font-medium">Documents</h1>
|
||||||
|
<div className="ml-auto flex items-center gap-2">
|
||||||
|
<Button variant="ghost" asChild size="sm" className="hidden sm:flex">
|
||||||
|
<a
|
||||||
|
href="https://github.com/shadcn-ui/ui/tree/main/apps/v4/app/(examples)/dashboard"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
target="_blank"
|
||||||
|
className="dark:text-foreground"
|
||||||
|
>
|
||||||
|
GitHub
|
||||||
|
</a>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
);
|
||||||
|
}
|
||||||
67
apps/react/src/components/theme-provider.tsx
Normal file
67
apps/react/src/components/theme-provider.tsx
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import { createContext, useContext, useEffect, useState } from "react";
|
||||||
|
|
||||||
|
type Theme = "dark" | "light" | "system";
|
||||||
|
|
||||||
|
type ThemeProviderProps = {
|
||||||
|
children: React.ReactNode;
|
||||||
|
defaultTheme?: Theme;
|
||||||
|
storageKey?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ThemeProviderState = {
|
||||||
|
theme: Theme;
|
||||||
|
setTheme: (theme: Theme) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const initialState: ThemeProviderState = {
|
||||||
|
theme: "system",
|
||||||
|
setTheme: () => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
|
||||||
|
|
||||||
|
export function ThemeProvider({
|
||||||
|
children,
|
||||||
|
defaultTheme = "system",
|
||||||
|
storageKey = "vite-ui-theme",
|
||||||
|
...props
|
||||||
|
}: ThemeProviderProps) {
|
||||||
|
const [theme, setTheme] = useState<Theme>(() => (localStorage.getItem(storageKey) as Theme) || defaultTheme);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const root = window.document.documentElement;
|
||||||
|
|
||||||
|
root.classList.remove("light", "dark");
|
||||||
|
|
||||||
|
if (theme === "system") {
|
||||||
|
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
||||||
|
|
||||||
|
root.classList.add(systemTheme);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
root.classList.add(theme);
|
||||||
|
}, [theme]);
|
||||||
|
|
||||||
|
const value = {
|
||||||
|
theme,
|
||||||
|
setTheme: (theme: Theme) => {
|
||||||
|
localStorage.setItem(storageKey, theme);
|
||||||
|
setTheme(theme);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ThemeProviderContext.Provider {...props} value={value}>
|
||||||
|
{children}
|
||||||
|
</ThemeProviderContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useTheme = () => {
|
||||||
|
const context = useContext(ThemeProviderContext);
|
||||||
|
|
||||||
|
if (context === undefined) throw new Error("useTheme must be used within a ThemeProvider");
|
||||||
|
|
||||||
|
return context;
|
||||||
|
};
|
||||||
38
apps/react/src/components/ui/avatar.tsx
Normal file
38
apps/react/src/components/ui/avatar.tsx
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import * as AvatarPrimitive from "@radix-ui/react-avatar";
|
||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "../../libraries/utils.ts";
|
||||||
|
|
||||||
|
const Avatar = React.forwardRef<
|
||||||
|
React.ElementRef<typeof AvatarPrimitive.Root>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<AvatarPrimitive.Root
|
||||||
|
ref={ref}
|
||||||
|
className={cn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
Avatar.displayName = AvatarPrimitive.Root.displayName;
|
||||||
|
|
||||||
|
const AvatarImage = React.forwardRef<
|
||||||
|
React.ElementRef<typeof AvatarPrimitive.Image>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<AvatarPrimitive.Image ref={ref} className={cn("aspect-square h-full w-full", className)} {...props} />
|
||||||
|
));
|
||||||
|
AvatarImage.displayName = AvatarPrimitive.Image.displayName;
|
||||||
|
|
||||||
|
const AvatarFallback = React.forwardRef<
|
||||||
|
React.ElementRef<typeof AvatarPrimitive.Fallback>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<AvatarPrimitive.Fallback
|
||||||
|
ref={ref}
|
||||||
|
className={cn("flex h-full w-full items-center justify-center rounded-full bg-muted", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;
|
||||||
|
|
||||||
|
export { Avatar, AvatarImage, AvatarFallback };
|
||||||
47
apps/react/src/components/ui/button.tsx
Normal file
47
apps/react/src/components/ui/button.tsx
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import { Slot } from "@radix-ui/react-slot";
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "../../libraries/utils.ts";
|
||||||
|
|
||||||
|
const buttonVariants = cva(
|
||||||
|
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
|
||||||
|
destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
|
||||||
|
outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
|
||||||
|
secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
|
||||||
|
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||||
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default: "h-9 px-4 py-2",
|
||||||
|
sm: "h-8 rounded-md px-3 text-xs",
|
||||||
|
lg: "h-10 rounded-md px-8",
|
||||||
|
icon: "h-9 w-9",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "default",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export interface ButtonProps
|
||||||
|
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||||
|
VariantProps<typeof buttonVariants> {
|
||||||
|
asChild?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||||
|
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||||
|
const Comp = asChild ? Slot : "button";
|
||||||
|
return <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
Button.displayName = "Button";
|
||||||
|
|
||||||
|
export { Button, buttonVariants };
|
||||||
180
apps/react/src/components/ui/dropdown-menu.tsx
Normal file
180
apps/react/src/components/ui/dropdown-menu.tsx
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
|
||||||
|
import { Check, ChevronRight, Circle } from "lucide-react";
|
||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "../../libraries/utils.ts";
|
||||||
|
|
||||||
|
const DropdownMenu = DropdownMenuPrimitive.Root;
|
||||||
|
|
||||||
|
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
|
||||||
|
|
||||||
|
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
|
||||||
|
|
||||||
|
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
|
||||||
|
|
||||||
|
const DropdownMenuSub = DropdownMenuPrimitive.Sub;
|
||||||
|
|
||||||
|
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
|
||||||
|
|
||||||
|
const DropdownMenuSubTrigger = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||||
|
inset?: boolean;
|
||||||
|
}
|
||||||
|
>(({ className, inset, children, ...props }, ref) => (
|
||||||
|
<DropdownMenuPrimitive.SubTrigger
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||||
|
inset && "pl-8",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronRight className="ml-auto" />
|
||||||
|
</DropdownMenuPrimitive.SubTrigger>
|
||||||
|
));
|
||||||
|
DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName;
|
||||||
|
|
||||||
|
const DropdownMenuSubContent = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<DropdownMenuPrimitive.SubContent
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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 origin-[--radix-dropdown-menu-content-transform-origin]",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName;
|
||||||
|
|
||||||
|
const DropdownMenuContent = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
|
||||||
|
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||||
|
<DropdownMenuPrimitive.Portal>
|
||||||
|
<DropdownMenuPrimitive.Content
|
||||||
|
ref={ref}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className={cn(
|
||||||
|
"z-50 max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
|
||||||
|
"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 origin-[--radix-dropdown-menu-content-transform-origin]",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</DropdownMenuPrimitive.Portal>
|
||||||
|
));
|
||||||
|
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
|
||||||
|
|
||||||
|
const DropdownMenuItem = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
|
||||||
|
inset?: boolean;
|
||||||
|
}
|
||||||
|
>(({ className, inset, ...props }, ref) => (
|
||||||
|
<DropdownMenuPrimitive.Item
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||||
|
inset && "pl-8",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
|
||||||
|
|
||||||
|
const DropdownMenuCheckboxItem = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
|
||||||
|
>(({ className, children, checked, ...props }, ref) => (
|
||||||
|
<DropdownMenuPrimitive.CheckboxItem
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
checked={checked}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||||
|
<DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
<Check className="h-4 w-4" />
|
||||||
|
</DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</DropdownMenuPrimitive.CheckboxItem>
|
||||||
|
));
|
||||||
|
DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName;
|
||||||
|
|
||||||
|
const DropdownMenuRadioItem = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
|
||||||
|
>(({ className, children, ...props }, ref) => (
|
||||||
|
<DropdownMenuPrimitive.RadioItem
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||||
|
<DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
<Circle className="h-2 w-2 fill-current" />
|
||||||
|
</DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</DropdownMenuPrimitive.RadioItem>
|
||||||
|
));
|
||||||
|
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
|
||||||
|
|
||||||
|
const DropdownMenuLabel = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
|
||||||
|
inset?: boolean;
|
||||||
|
}
|
||||||
|
>(({ className, inset, ...props }, ref) => (
|
||||||
|
<DropdownMenuPrimitive.Label
|
||||||
|
ref={ref}
|
||||||
|
className={cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
|
||||||
|
|
||||||
|
const DropdownMenuSeparator = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<DropdownMenuPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-muted", className)} {...props} />
|
||||||
|
));
|
||||||
|
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
|
||||||
|
|
||||||
|
const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
|
||||||
|
return <span className={cn("ml-auto text-xs tracking-widest opacity-60", className)} {...props} />;
|
||||||
|
};
|
||||||
|
DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
|
||||||
|
|
||||||
|
export {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuCheckboxItem,
|
||||||
|
DropdownMenuRadioItem,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuShortcut,
|
||||||
|
DropdownMenuGroup,
|
||||||
|
DropdownMenuPortal,
|
||||||
|
DropdownMenuSub,
|
||||||
|
DropdownMenuSubContent,
|
||||||
|
DropdownMenuSubTrigger,
|
||||||
|
DropdownMenuRadioGroup,
|
||||||
|
};
|
||||||
21
apps/react/src/components/ui/input.tsx
Normal file
21
apps/react/src/components/ui/input.tsx
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/libraries/utils";
|
||||||
|
|
||||||
|
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
type={type}
|
||||||
|
data-slot="input"
|
||||||
|
className={cn(
|
||||||
|
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||||
|
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||||
|
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Input };
|
||||||
38
apps/react/src/components/ui/scroll-area.tsx
Normal file
38
apps/react/src/components/ui/scroll-area.tsx
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
|
||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/libraries/utils";
|
||||||
|
|
||||||
|
const ScrollArea = React.forwardRef<
|
||||||
|
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
|
||||||
|
>(({ className, children, ...props }, ref) => (
|
||||||
|
<ScrollAreaPrimitive.Root ref={ref} className={cn("relative overflow-hidden", className)} {...props}>
|
||||||
|
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">{children}</ScrollAreaPrimitive.Viewport>
|
||||||
|
<ScrollBar />
|
||||||
|
<ScrollAreaPrimitive.Corner />
|
||||||
|
</ScrollAreaPrimitive.Root>
|
||||||
|
));
|
||||||
|
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
|
||||||
|
|
||||||
|
const ScrollBar = React.forwardRef<
|
||||||
|
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||||
|
>(({ className, orientation = "vertical", ...props }, ref) => (
|
||||||
|
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||||
|
ref={ref}
|
||||||
|
orientation={orientation}
|
||||||
|
className={cn(
|
||||||
|
"flex touch-none select-none transition-colors",
|
||||||
|
orientation === "vertical" && "h-full w-2.5 border-l border-l-transparent p-[1px]",
|
||||||
|
orientation === "horizontal" && "h-2.5 flex-col border-t border-t-transparent p-[1px]",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
|
||||||
|
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||||
|
));
|
||||||
|
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
|
||||||
|
|
||||||
|
export { ScrollArea, ScrollBar };
|
||||||
26
apps/react/src/components/ui/separator.tsx
Normal file
26
apps/react/src/components/ui/separator.tsx
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import * as SeparatorPrimitive from "@radix-ui/react-separator";
|
||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/libraries/utils";
|
||||||
|
|
||||||
|
function Separator({
|
||||||
|
className,
|
||||||
|
orientation = "horizontal",
|
||||||
|
decorative = true,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<SeparatorPrimitive.Root
|
||||||
|
data-slot="separator"
|
||||||
|
decorative={decorative}
|
||||||
|
orientation={orientation}
|
||||||
|
className={cn(
|
||||||
|
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Separator };
|
||||||
103
apps/react/src/components/ui/sheet.tsx
Normal file
103
apps/react/src/components/ui/sheet.tsx
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as SheetPrimitive from "@radix-ui/react-dialog";
|
||||||
|
import { XIcon } from "lucide-react";
|
||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/libraries/utils";
|
||||||
|
|
||||||
|
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||||
|
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetTrigger({ ...props }: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
||||||
|
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetClose({ ...props }: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
||||||
|
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetPortal({ ...props }: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
||||||
|
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetOverlay({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
|
||||||
|
return (
|
||||||
|
<SheetPrimitive.Overlay
|
||||||
|
data-slot="sheet-overlay"
|
||||||
|
className={cn(
|
||||||
|
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
side = "right",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
||||||
|
side?: "top" | "right" | "bottom" | "left";
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<SheetPortal>
|
||||||
|
<SheetOverlay />
|
||||||
|
<SheetPrimitive.Content
|
||||||
|
data-slot="sheet-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
||||||
|
side === "right" &&
|
||||||
|
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
|
||||||
|
side === "left" &&
|
||||||
|
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
|
||||||
|
side === "top" &&
|
||||||
|
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
|
||||||
|
side === "bottom" &&
|
||||||
|
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
|
||||||
|
<XIcon className="size-4" />
|
||||||
|
<span className="sr-only">Close</span>
|
||||||
|
</SheetPrimitive.Close>
|
||||||
|
</SheetPrimitive.Content>
|
||||||
|
</SheetPortal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return <div data-slot="sheet-header" className={cn("flex flex-col gap-1.5 p-4", className)} {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return <div data-slot="sheet-footer" className={cn("mt-auto flex flex-col gap-2 p-4", className)} {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetTitle({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
||||||
|
return (
|
||||||
|
<SheetPrimitive.Title
|
||||||
|
data-slot="sheet-title"
|
||||||
|
className={cn("text-foreground font-semibold", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetDescription({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Description>) {
|
||||||
|
return (
|
||||||
|
<SheetPrimitive.Description
|
||||||
|
data-slot="sheet-description"
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Sheet, SheetTrigger, SheetClose, SheetContent, SheetHeader, SheetFooter, SheetTitle, SheetDescription };
|
||||||
643
apps/react/src/components/ui/sidebar.tsx
Normal file
643
apps/react/src/components/ui/sidebar.tsx
Normal file
@@ -0,0 +1,643 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Slot } from "@radix-ui/react-slot";
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
|
import { PanelLeft } from "lucide-react";
|
||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Separator } from "@/components/ui/separator";
|
||||||
|
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||||
|
import { useIsMobile } from "@/hooks/use-mobile";
|
||||||
|
import { cn } from "@/libraries/utils";
|
||||||
|
|
||||||
|
const SIDEBAR_COOKIE_NAME = "sidebar_state";
|
||||||
|
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
|
||||||
|
const SIDEBAR_WIDTH = "16rem";
|
||||||
|
const SIDEBAR_WIDTH_MOBILE = "18rem";
|
||||||
|
const SIDEBAR_WIDTH_ICON = "3rem";
|
||||||
|
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
|
||||||
|
|
||||||
|
type SidebarContextProps = {
|
||||||
|
state: "expanded" | "collapsed";
|
||||||
|
open: boolean;
|
||||||
|
setOpen: (open: boolean) => void;
|
||||||
|
openMobile: boolean;
|
||||||
|
setOpenMobile: (open: boolean) => void;
|
||||||
|
isMobile: boolean;
|
||||||
|
toggleSidebar: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const SidebarContext = React.createContext<SidebarContextProps | null>(null);
|
||||||
|
|
||||||
|
function useSidebar() {
|
||||||
|
const context = React.useContext(SidebarContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error("useSidebar must be used within a SidebarProvider.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SidebarProvider = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.ComponentProps<"div"> & {
|
||||||
|
defaultOpen?: boolean;
|
||||||
|
open?: boolean;
|
||||||
|
onOpenChange?: (open: boolean) => void;
|
||||||
|
}
|
||||||
|
>(({ defaultOpen = true, open: openProp, onOpenChange: setOpenProp, className, style, children, ...props }, ref) => {
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
const [openMobile, setOpenMobile] = React.useState(false);
|
||||||
|
|
||||||
|
// This is the internal state of the sidebar.
|
||||||
|
// We use openProp and setOpenProp for control from outside the component.
|
||||||
|
const [_open, _setOpen] = React.useState(defaultOpen);
|
||||||
|
const open = openProp ?? _open;
|
||||||
|
const setOpen = React.useCallback(
|
||||||
|
(value: boolean | ((value: boolean) => boolean)) => {
|
||||||
|
const openState = typeof value === "function" ? value(open) : value;
|
||||||
|
if (setOpenProp) {
|
||||||
|
setOpenProp(openState);
|
||||||
|
} else {
|
||||||
|
_setOpen(openState);
|
||||||
|
}
|
||||||
|
|
||||||
|
// This sets the cookie to keep the sidebar state.
|
||||||
|
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
|
||||||
|
},
|
||||||
|
[setOpenProp, open],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Helper to toggle the sidebar.
|
||||||
|
const toggleSidebar = React.useCallback(() => {
|
||||||
|
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
|
||||||
|
}, [isMobile, setOpen, setOpenMobile]);
|
||||||
|
|
||||||
|
// Adds a keyboard shortcut to toggle the sidebar.
|
||||||
|
React.useEffect(() => {
|
||||||
|
const handleKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (event.key === SIDEBAR_KEYBOARD_SHORTCUT && (event.metaKey || event.ctrlKey)) {
|
||||||
|
event.preventDefault();
|
||||||
|
toggleSidebar();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener("keydown", handleKeyDown);
|
||||||
|
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||||
|
}, [toggleSidebar]);
|
||||||
|
|
||||||
|
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||||
|
// This makes it easier to style the sidebar with Tailwind classes.
|
||||||
|
const state = open ? "expanded" : "collapsed";
|
||||||
|
|
||||||
|
const contextValue = React.useMemo<SidebarContextProps>(
|
||||||
|
() => ({
|
||||||
|
state,
|
||||||
|
open,
|
||||||
|
setOpen,
|
||||||
|
isMobile,
|
||||||
|
openMobile,
|
||||||
|
setOpenMobile,
|
||||||
|
toggleSidebar,
|
||||||
|
}),
|
||||||
|
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SidebarContext.Provider value={contextValue}>
|
||||||
|
<TooltipProvider delayDuration={0}>
|
||||||
|
<div
|
||||||
|
style={
|
||||||
|
{
|
||||||
|
"--sidebar-width": SIDEBAR_WIDTH,
|
||||||
|
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||||
|
...style,
|
||||||
|
} as React.CSSProperties
|
||||||
|
}
|
||||||
|
className={cn("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar", className)}
|
||||||
|
ref={ref}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</TooltipProvider>
|
||||||
|
</SidebarContext.Provider>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarProvider.displayName = "SidebarProvider";
|
||||||
|
|
||||||
|
const Sidebar = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.ComponentProps<"div"> & {
|
||||||
|
side?: "left" | "right";
|
||||||
|
variant?: "sidebar" | "floating" | "inset";
|
||||||
|
collapsible?: "offcanvas" | "icon" | "none";
|
||||||
|
}
|
||||||
|
>(({ side = "left", variant = "sidebar", collapsible = "offcanvas", className, children, ...props }, ref) => {
|
||||||
|
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
|
||||||
|
|
||||||
|
if (collapsible === "none") {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground", className)}
|
||||||
|
ref={ref}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isMobile) {
|
||||||
|
return (
|
||||||
|
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||||
|
<SheetContent
|
||||||
|
data-sidebar="sidebar"
|
||||||
|
data-mobile="true"
|
||||||
|
className="w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
|
||||||
|
style={
|
||||||
|
{
|
||||||
|
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||||
|
} as React.CSSProperties
|
||||||
|
}
|
||||||
|
side={side}
|
||||||
|
>
|
||||||
|
<SheetHeader className="sr-only">
|
||||||
|
<SheetTitle>Sidebar</SheetTitle>
|
||||||
|
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
|
||||||
|
</SheetHeader>
|
||||||
|
<div className="flex h-full w-full flex-col">{children}</div>
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
className="group peer hidden text-sidebar-foreground md:block"
|
||||||
|
data-state={state}
|
||||||
|
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||||
|
data-variant={variant}
|
||||||
|
data-side={side}
|
||||||
|
>
|
||||||
|
{/* This is what handles the sidebar gap on desktop */}
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"relative w-[--sidebar-width] bg-transparent transition-[width] duration-200 ease-linear",
|
||||||
|
"group-data-[collapsible=offcanvas]:w-0",
|
||||||
|
"group-data-[side=right]:rotate-180",
|
||||||
|
variant === "floating" || variant === "inset"
|
||||||
|
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]"
|
||||||
|
: "group-data-[collapsible=icon]:w-[--sidebar-width-icon]",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||||
|
side === "left"
|
||||||
|
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||||
|
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||||
|
// Adjust the padding for floating and inset variants.
|
||||||
|
variant === "floating" || variant === "inset"
|
||||||
|
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]"
|
||||||
|
: "group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
data-sidebar="sidebar"
|
||||||
|
className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow"
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
Sidebar.displayName = "Sidebar";
|
||||||
|
|
||||||
|
const SidebarTrigger = React.forwardRef<React.ElementRef<typeof Button>, React.ComponentProps<typeof Button>>(
|
||||||
|
({ className, onClick, ...props }, ref) => {
|
||||||
|
const { toggleSidebar } = useSidebar();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="trigger"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className={cn("h-7 w-7", className)}
|
||||||
|
onClick={(event) => {
|
||||||
|
onClick?.(event);
|
||||||
|
toggleSidebar();
|
||||||
|
}}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<PanelLeft />
|
||||||
|
<span className="sr-only">Toggle Sidebar</span>
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
SidebarTrigger.displayName = "SidebarTrigger";
|
||||||
|
|
||||||
|
const SidebarRail = React.forwardRef<HTMLButtonElement, React.ComponentProps<"button">>(
|
||||||
|
({ className, ...props }, ref) => {
|
||||||
|
const { toggleSidebar } = useSidebar();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="rail"
|
||||||
|
aria-label="Toggle Sidebar"
|
||||||
|
tabIndex={-1}
|
||||||
|
onClick={toggleSidebar}
|
||||||
|
title="Toggle Sidebar"
|
||||||
|
className={cn(
|
||||||
|
"absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex",
|
||||||
|
"[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize",
|
||||||
|
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||||
|
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar",
|
||||||
|
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||||
|
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
SidebarRail.displayName = "SidebarRail";
|
||||||
|
|
||||||
|
const SidebarInset = React.forwardRef<HTMLDivElement, React.ComponentProps<"main">>(({ className, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<main
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"relative flex w-full flex-1 flex-col bg-background",
|
||||||
|
"md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarInset.displayName = "SidebarInset";
|
||||||
|
|
||||||
|
const SidebarInput = React.forwardRef<React.ElementRef<typeof Input>, React.ComponentProps<typeof Input>>(
|
||||||
|
({ className, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<Input
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="input"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
SidebarInput.displayName = "SidebarInput";
|
||||||
|
|
||||||
|
const SidebarHeader = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(({ className, ...props }, ref) => {
|
||||||
|
return <div ref={ref} data-sidebar="header" className={cn("flex flex-col gap-2 p-2", className)} {...props} />;
|
||||||
|
});
|
||||||
|
SidebarHeader.displayName = "SidebarHeader";
|
||||||
|
|
||||||
|
const SidebarFooter = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(({ className, ...props }, ref) => {
|
||||||
|
return <div ref={ref} data-sidebar="footer" className={cn("flex flex-col gap-2 p-2", className)} {...props} />;
|
||||||
|
});
|
||||||
|
SidebarFooter.displayName = "SidebarFooter";
|
||||||
|
|
||||||
|
const SidebarSeparator = React.forwardRef<React.ElementRef<typeof Separator>, React.ComponentProps<typeof Separator>>(
|
||||||
|
({ className, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<Separator
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="separator"
|
||||||
|
className={cn("mx-2 w-auto bg-sidebar-border", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
SidebarSeparator.displayName = "SidebarSeparator";
|
||||||
|
|
||||||
|
const SidebarContent = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(({ className, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="content"
|
||||||
|
className={cn(
|
||||||
|
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarContent.displayName = "SidebarContent";
|
||||||
|
|
||||||
|
const SidebarGroup = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(({ className, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="group"
|
||||||
|
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarGroup.displayName = "SidebarGroup";
|
||||||
|
|
||||||
|
const SidebarGroupLabel = React.forwardRef<HTMLDivElement, React.ComponentProps<"div"> & { asChild?: boolean }>(
|
||||||
|
({ className, asChild = false, ...props }, ref) => {
|
||||||
|
const Comp = asChild ? Slot : "div";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="group-label"
|
||||||
|
className={cn(
|
||||||
|
"flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||||
|
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
SidebarGroupLabel.displayName = "SidebarGroupLabel";
|
||||||
|
|
||||||
|
const SidebarGroupAction = React.forwardRef<HTMLButtonElement, React.ComponentProps<"button"> & { asChild?: boolean }>(
|
||||||
|
({ className, asChild = false, ...props }, ref) => {
|
||||||
|
const Comp = asChild ? Slot : "button";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="group-action"
|
||||||
|
className={cn(
|
||||||
|
"absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||||
|
// Increases the hit area of the button on mobile.
|
||||||
|
"after:absolute after:-inset-2 after:md:hidden",
|
||||||
|
"group-data-[collapsible=icon]:hidden",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
SidebarGroupAction.displayName = "SidebarGroupAction";
|
||||||
|
|
||||||
|
const SidebarGroupContent = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(
|
||||||
|
({ className, ...props }, ref) => (
|
||||||
|
<div ref={ref} data-sidebar="group-content" className={cn("w-full text-sm", className)} {...props} />
|
||||||
|
),
|
||||||
|
);
|
||||||
|
SidebarGroupContent.displayName = "SidebarGroupContent";
|
||||||
|
|
||||||
|
const SidebarMenu = React.forwardRef<HTMLUListElement, React.ComponentProps<"ul">>(({ className, ...props }, ref) => (
|
||||||
|
<ul ref={ref} data-sidebar="menu" className={cn("flex w-full min-w-0 flex-col gap-1", className)} {...props} />
|
||||||
|
));
|
||||||
|
SidebarMenu.displayName = "SidebarMenu";
|
||||||
|
|
||||||
|
const SidebarMenuItem = React.forwardRef<HTMLLIElement, React.ComponentProps<"li">>(({ className, ...props }, ref) => (
|
||||||
|
<li ref={ref} data-sidebar="menu-item" className={cn("group/menu-item relative", className)} {...props} />
|
||||||
|
));
|
||||||
|
SidebarMenuItem.displayName = "SidebarMenuItem";
|
||||||
|
|
||||||
|
const sidebarMenuButtonVariants = cva(
|
||||||
|
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||||
|
outline:
|
||||||
|
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default: "h-8 text-sm",
|
||||||
|
sm: "h-7 text-xs",
|
||||||
|
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "default",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const SidebarMenuButton = React.forwardRef<
|
||||||
|
HTMLButtonElement,
|
||||||
|
React.ComponentProps<"button"> & {
|
||||||
|
asChild?: boolean;
|
||||||
|
isActive?: boolean;
|
||||||
|
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
|
||||||
|
} & VariantProps<typeof sidebarMenuButtonVariants>
|
||||||
|
>(({ asChild = false, isActive = false, variant = "default", size = "default", tooltip, className, ...props }, ref) => {
|
||||||
|
const Comp = asChild ? Slot : "button";
|
||||||
|
const { isMobile, state } = useSidebar();
|
||||||
|
|
||||||
|
const button = (
|
||||||
|
<Comp
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="menu-button"
|
||||||
|
data-size={size}
|
||||||
|
data-active={isActive}
|
||||||
|
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!tooltip) {
|
||||||
|
return button;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof tooltip === "string") {
|
||||||
|
tooltip = {
|
||||||
|
children: tooltip,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||||
|
<TooltipContent side="right" align="center" hidden={state !== "collapsed" || isMobile} {...tooltip} />
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarMenuButton.displayName = "SidebarMenuButton";
|
||||||
|
|
||||||
|
const SidebarMenuAction = React.forwardRef<
|
||||||
|
HTMLButtonElement,
|
||||||
|
React.ComponentProps<"button"> & {
|
||||||
|
asChild?: boolean;
|
||||||
|
showOnHover?: boolean;
|
||||||
|
}
|
||||||
|
>(({ className, asChild = false, showOnHover = false, ...props }, ref) => {
|
||||||
|
const Comp = asChild ? Slot : "button";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="menu-action"
|
||||||
|
className={cn(
|
||||||
|
"absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0",
|
||||||
|
// Increases the hit area of the button on mobile.
|
||||||
|
"after:absolute after:-inset-2 after:md:hidden",
|
||||||
|
"peer-data-[size=sm]/menu-button:top-1",
|
||||||
|
"peer-data-[size=default]/menu-button:top-1.5",
|
||||||
|
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||||
|
"group-data-[collapsible=icon]:hidden",
|
||||||
|
showOnHover &&
|
||||||
|
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarMenuAction.displayName = "SidebarMenuAction";
|
||||||
|
|
||||||
|
const SidebarMenuBadge = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(
|
||||||
|
({ className, ...props }, ref) => (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="menu-badge"
|
||||||
|
className={cn(
|
||||||
|
"pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground",
|
||||||
|
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
|
||||||
|
"peer-data-[size=sm]/menu-button:top-1",
|
||||||
|
"peer-data-[size=default]/menu-button:top-1.5",
|
||||||
|
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||||
|
"group-data-[collapsible=icon]:hidden",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
);
|
||||||
|
SidebarMenuBadge.displayName = "SidebarMenuBadge";
|
||||||
|
|
||||||
|
const SidebarMenuSkeleton = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.ComponentProps<"div"> & {
|
||||||
|
showIcon?: boolean;
|
||||||
|
}
|
||||||
|
>(({ className, showIcon = false, ...props }, ref) => {
|
||||||
|
// Random width between 50 to 90%.
|
||||||
|
const width = React.useMemo(() => {
|
||||||
|
return `${Math.floor(Math.random() * 40) + 50}%`;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="menu-skeleton"
|
||||||
|
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{showIcon && <Skeleton className="size-4 rounded-md" data-sidebar="menu-skeleton-icon" />}
|
||||||
|
<Skeleton
|
||||||
|
className="h-4 max-w-[--skeleton-width] flex-1"
|
||||||
|
data-sidebar="menu-skeleton-text"
|
||||||
|
style={
|
||||||
|
{
|
||||||
|
"--skeleton-width": width,
|
||||||
|
} as React.CSSProperties
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarMenuSkeleton.displayName = "SidebarMenuSkeleton";
|
||||||
|
|
||||||
|
const SidebarMenuSub = React.forwardRef<HTMLUListElement, React.ComponentProps<"ul">>(
|
||||||
|
({ className, ...props }, ref) => (
|
||||||
|
<ul
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="menu-sub"
|
||||||
|
className={cn(
|
||||||
|
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5",
|
||||||
|
"group-data-[collapsible=icon]:hidden",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
);
|
||||||
|
SidebarMenuSub.displayName = "SidebarMenuSub";
|
||||||
|
|
||||||
|
const SidebarMenuSubItem = React.forwardRef<HTMLLIElement, React.ComponentProps<"li">>(({ ...props }, ref) => (
|
||||||
|
<li ref={ref} {...props} />
|
||||||
|
));
|
||||||
|
SidebarMenuSubItem.displayName = "SidebarMenuSubItem";
|
||||||
|
|
||||||
|
const SidebarMenuSubButton = React.forwardRef<
|
||||||
|
HTMLAnchorElement,
|
||||||
|
React.ComponentProps<"a"> & {
|
||||||
|
asChild?: boolean;
|
||||||
|
size?: "sm" | "md";
|
||||||
|
isActive?: boolean;
|
||||||
|
}
|
||||||
|
>(({ asChild = false, size = "md", isActive, className, ...props }, ref) => {
|
||||||
|
const Comp = asChild ? Slot : "a";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="menu-sub-button"
|
||||||
|
data-size={size}
|
||||||
|
data-active={isActive}
|
||||||
|
className={cn(
|
||||||
|
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
|
||||||
|
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||||
|
size === "sm" && "text-xs",
|
||||||
|
size === "md" && "text-sm",
|
||||||
|
"group-data-[collapsible=icon]:hidden",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarMenuSubButton.displayName = "SidebarMenuSubButton";
|
||||||
|
|
||||||
|
export {
|
||||||
|
Sidebar,
|
||||||
|
SidebarContent,
|
||||||
|
SidebarFooter,
|
||||||
|
SidebarGroup,
|
||||||
|
SidebarGroupAction,
|
||||||
|
SidebarGroupContent,
|
||||||
|
SidebarGroupLabel,
|
||||||
|
SidebarHeader,
|
||||||
|
SidebarInput,
|
||||||
|
SidebarInset,
|
||||||
|
SidebarMenu,
|
||||||
|
SidebarMenuAction,
|
||||||
|
SidebarMenuBadge,
|
||||||
|
SidebarMenuButton,
|
||||||
|
SidebarMenuItem,
|
||||||
|
SidebarMenuSkeleton,
|
||||||
|
SidebarMenuSub,
|
||||||
|
SidebarMenuSubButton,
|
||||||
|
SidebarMenuSubItem,
|
||||||
|
SidebarProvider,
|
||||||
|
SidebarRail,
|
||||||
|
SidebarSeparator,
|
||||||
|
SidebarTrigger,
|
||||||
|
useSidebar,
|
||||||
|
};
|
||||||
7
apps/react/src/components/ui/skeleton.tsx
Normal file
7
apps/react/src/components/ui/skeleton.tsx
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { cn } from "@/libraries/utils";
|
||||||
|
|
||||||
|
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return <div data-slot="skeleton" className={cn("bg-accent animate-pulse rounded-md", className)} {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Skeleton };
|
||||||
46
apps/react/src/components/ui/tooltip.tsx
Normal file
46
apps/react/src/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
|
||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/libraries/utils";
|
||||||
|
|
||||||
|
function TooltipProvider({ delayDuration = 0, ...props }: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||||
|
return <TooltipPrimitive.Provider data-slot="tooltip-provider" delayDuration={delayDuration} {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<TooltipProvider>
|
||||||
|
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||||
|
</TooltipProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||||
|
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function TooltipContent({
|
||||||
|
className,
|
||||||
|
sideOffset = 0,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<TooltipPrimitive.Portal>
|
||||||
|
<TooltipPrimitive.Content
|
||||||
|
data-slot="tooltip-content"
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className={cn(
|
||||||
|
"bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
||||||
|
</TooltipPrimitive.Content>
|
||||||
|
</TooltipPrimitive.Portal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
|
||||||
19
apps/react/src/hooks/use-mobile.ts
Normal file
19
apps/react/src/hooks/use-mobile.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
const MOBILE_BREAKPOINT = 768;
|
||||||
|
|
||||||
|
export function useIsMobile() {
|
||||||
|
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
||||||
|
const onChange = () => {
|
||||||
|
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||||
|
};
|
||||||
|
mql.addEventListener("change", onChange);
|
||||||
|
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||||
|
return () => mql.removeEventListener("change", onChange);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return !!isMobile;
|
||||||
|
}
|
||||||
@@ -1 +1,122 @@
|
|||||||
@import "tailwindcss";
|
@import "tailwindcss";
|
||||||
|
|
||||||
|
@plugin "tailwindcss-animate";
|
||||||
|
@import "tw-animate-css";
|
||||||
|
|
||||||
|
@custom-variant dark (&:is(.dark *));
|
||||||
|
|
||||||
|
@theme inline {
|
||||||
|
--radius-sm: calc(var(--radius) - 4px);
|
||||||
|
--radius-md: calc(var(--radius) - 2px);
|
||||||
|
--radius-lg: var(--radius);
|
||||||
|
--radius-xl: calc(var(--radius) + 4px);
|
||||||
|
--color-background: var(--background);
|
||||||
|
--color-foreground: var(--foreground);
|
||||||
|
--color-card: var(--card);
|
||||||
|
--color-card-foreground: var(--card-foreground);
|
||||||
|
--color-popover: var(--popover);
|
||||||
|
--color-popover-foreground: var(--popover-foreground);
|
||||||
|
--color-primary: var(--primary);
|
||||||
|
--color-primary-foreground: var(--primary-foreground);
|
||||||
|
--color-secondary: var(--secondary);
|
||||||
|
--color-secondary-foreground: var(--secondary-foreground);
|
||||||
|
--color-muted: var(--muted);
|
||||||
|
--color-muted-foreground: var(--muted-foreground);
|
||||||
|
--color-accent: var(--accent);
|
||||||
|
--color-accent-foreground: var(--accent-foreground);
|
||||||
|
--color-destructive: var(--destructive);
|
||||||
|
--color-border: var(--border);
|
||||||
|
--color-input: var(--input);
|
||||||
|
--color-ring: var(--ring);
|
||||||
|
--color-chart-1: var(--chart-1);
|
||||||
|
--color-chart-2: var(--chart-2);
|
||||||
|
--color-chart-3: var(--chart-3);
|
||||||
|
--color-chart-4: var(--chart-4);
|
||||||
|
--color-chart-5: var(--chart-5);
|
||||||
|
--color-sidebar: var(--sidebar);
|
||||||
|
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||||
|
--color-sidebar-primary: var(--sidebar-primary);
|
||||||
|
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||||
|
--color-sidebar-accent: var(--sidebar-accent);
|
||||||
|
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||||
|
--color-sidebar-border: var(--sidebar-border);
|
||||||
|
--color-sidebar-ring: var(--sidebar-ring);
|
||||||
|
}
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--radius: 0.625rem;
|
||||||
|
--background: oklch(1 0 0);
|
||||||
|
--foreground: oklch(0.145 0 0);
|
||||||
|
--card: oklch(1 0 0);
|
||||||
|
--card-foreground: oklch(0.145 0 0);
|
||||||
|
--popover: oklch(1 0 0);
|
||||||
|
--popover-foreground: oklch(0.145 0 0);
|
||||||
|
--primary: oklch(0.205 0 0);
|
||||||
|
--primary-foreground: oklch(0.985 0 0);
|
||||||
|
--secondary: oklch(0.97 0 0);
|
||||||
|
--secondary-foreground: oklch(0.205 0 0);
|
||||||
|
--muted: oklch(0.97 0 0);
|
||||||
|
--muted-foreground: oklch(0.556 0 0);
|
||||||
|
--accent: oklch(0.97 0 0);
|
||||||
|
--accent-foreground: oklch(0.205 0 0);
|
||||||
|
--destructive: oklch(0.577 0.245 27.325);
|
||||||
|
--border: oklch(0.922 0 0);
|
||||||
|
--input: oklch(0.922 0 0);
|
||||||
|
--ring: oklch(0.708 0 0);
|
||||||
|
--chart-1: oklch(0.646 0.222 41.116);
|
||||||
|
--chart-2: oklch(0.6 0.118 184.704);
|
||||||
|
--chart-3: oklch(0.398 0.07 227.392);
|
||||||
|
--chart-4: oklch(0.828 0.189 84.429);
|
||||||
|
--chart-5: oklch(0.769 0.188 70.08);
|
||||||
|
--sidebar: oklch(0.985 0 0);
|
||||||
|
--sidebar-foreground: oklch(0.145 0 0);
|
||||||
|
--sidebar-primary: oklch(0.205 0 0);
|
||||||
|
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-accent: oklch(0.97 0 0);
|
||||||
|
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||||
|
--sidebar-border: oklch(0.922 0 0);
|
||||||
|
--sidebar-ring: oklch(0.708 0 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark {
|
||||||
|
--background: oklch(0.145 0 0);
|
||||||
|
--foreground: oklch(0.985 0 0);
|
||||||
|
--card: oklch(0.205 0 0);
|
||||||
|
--card-foreground: oklch(0.985 0 0);
|
||||||
|
--popover: oklch(0.205 0 0);
|
||||||
|
--popover-foreground: oklch(0.985 0 0);
|
||||||
|
--primary: oklch(0.922 0 0);
|
||||||
|
--primary-foreground: oklch(0.205 0 0);
|
||||||
|
--secondary: oklch(0.269 0 0);
|
||||||
|
--secondary-foreground: oklch(0.985 0 0);
|
||||||
|
--muted: oklch(0.269 0 0);
|
||||||
|
--muted-foreground: oklch(0.708 0 0);
|
||||||
|
--accent: oklch(0.269 0 0);
|
||||||
|
--accent-foreground: oklch(0.985 0 0);
|
||||||
|
--destructive: oklch(0.704 0.191 22.216);
|
||||||
|
--border: oklch(1 0 0 / 10%);
|
||||||
|
--input: oklch(1 0 0 / 15%);
|
||||||
|
--ring: oklch(0.556 0 0);
|
||||||
|
--chart-1: oklch(0.488 0.243 264.376);
|
||||||
|
--chart-2: oklch(0.696 0.17 162.48);
|
||||||
|
--chart-3: oklch(0.769 0.188 70.08);
|
||||||
|
--chart-4: oklch(0.627 0.265 303.9);
|
||||||
|
--chart-5: oklch(0.645 0.246 16.439);
|
||||||
|
--sidebar: oklch(0.205 0 0);
|
||||||
|
--sidebar-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||||
|
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-accent: oklch(0.269 0 0);
|
||||||
|
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-border: oklch(1 0 0 / 10%);
|
||||||
|
--sidebar-ring: oklch(0.556 0 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer base {
|
||||||
|
* {
|
||||||
|
@apply border-border outline-ring/50;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
@apply bg-background text-foreground;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,372 +1,234 @@
|
|||||||
import type { ChangeEvent, Collection, SubscribeToMany, SubscribeToSingle, SubscriptionOptions } from "@valkyr/db";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import type { Subscription } from "@valkyr/event-emitter";
|
|
||||||
|
|
||||||
import { Debounce } from "./debounce.ts";
|
/**
|
||||||
import { ControllerRefs } from "./refs.ts";
|
* Minimal Controller for managing component state and lifecycle.
|
||||||
import type { ControllerClass, Empty, ReactComponent, ReservedPropertyMembers, Unknown } from "./types.ts";
|
*/
|
||||||
|
export class Controller<TState extends Record<string, unknown> = {}, TProps extends Record<string, unknown> = {}> {
|
||||||
export class Controller<TState extends Unknown = Empty, TProps extends Unknown = Empty> {
|
|
||||||
state: TState = {} as TState;
|
state: TState = {} as TState;
|
||||||
props: TProps = {} as TProps;
|
props: TProps = {} as TProps;
|
||||||
|
|
||||||
/**
|
|
||||||
* Stores a list of referenced elements identifies by a unique key.
|
|
||||||
*/
|
|
||||||
readonly refs = new ControllerRefs();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Records of event emitter subscriptions. They are keyed to a subscription name
|
|
||||||
* for easier identification when unsubscribing.
|
|
||||||
*/
|
|
||||||
readonly subscriptions = new Map<string, Subscription>();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Has the controller fully resolved the .onInit lifecycle method?
|
|
||||||
*/
|
|
||||||
#resolved = false;
|
#resolved = false;
|
||||||
|
#destroyed = false;
|
||||||
|
|
||||||
/**
|
#setState: (state: Partial<TState>) => void;
|
||||||
* Internal debounce instance used to ensure that we aren't triggering state
|
#setLoading: (state: boolean) => void;
|
||||||
* updates too frequently when updates are happening in quick succession.
|
|
||||||
*/
|
|
||||||
#debounce = new Debounce();
|
|
||||||
|
|
||||||
/**
|
constructor(setState: (state: Partial<TState>) => void, setLoading: (state: boolean) => void) {
|
||||||
* Creates a new controller instance with given default state and pushState
|
this.#setState = setState;
|
||||||
* handler method.
|
this.#setLoading = setLoading;
|
||||||
*
|
|
||||||
* @param state - Default state to assign to controller.
|
|
||||||
* @param pushData - Push data handler method.
|
|
||||||
*/
|
|
||||||
constructor(
|
|
||||||
readonly view: ReactComponent<TProps, any>,
|
|
||||||
readonly setView: any,
|
|
||||||
) {
|
|
||||||
this.query = this.query.bind(this);
|
|
||||||
this.subscribe = this.subscribe.bind(this);
|
|
||||||
this.setState = this.setState.bind(this);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Factories
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new controller instance using the given component and setView handler.
|
* Factory method to create a new controller instance.
|
||||||
*
|
|
||||||
* @param component - Component to render.
|
|
||||||
* @param setView - Method to provide a resolved view component.
|
|
||||||
*/
|
*/
|
||||||
static make<TController extends ControllerClass, TProps extends Unknown>(
|
static make<TController extends typeof Controller>(
|
||||||
this: TController,
|
this: TController,
|
||||||
component: ReactComponent<TProps, TController>,
|
setState: any,
|
||||||
setView: any,
|
setLoading: any,
|
||||||
): InstanceType<TController> {
|
): InstanceType<TController> {
|
||||||
return new Controller(component, setView);
|
return new this(setState, setLoading) as InstanceType<TController>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|--------------------------------------------------------------------------------
|
|--------------------------------------------------------------------------------
|
||||||
| Bootstrap & Teardown
|
| Lifecycle
|
||||||
|--------------------------------------------------------------------------------
|
|--------------------------------------------------------------------------------
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves the controller with given props.
|
||||||
|
* - First time: Runs onInit() then onResolve()
|
||||||
|
* - Subsequent times: Runs only onResolve()
|
||||||
|
*/
|
||||||
async $resolve(props: TProps): Promise<void> {
|
async $resolve(props: TProps): Promise<void> {
|
||||||
|
if (this.#destroyed === true) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
this.props = props;
|
this.props = props;
|
||||||
let state: Partial<TState> = {};
|
let state: Partial<TState> = {};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (this.#resolved === false) {
|
if (this.#resolved === false) {
|
||||||
state = {
|
const initState = await this.onInit();
|
||||||
...state,
|
if (initState) {
|
||||||
...((await this.onInit()) ?? {}),
|
state = { ...state, ...initState };
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
state = {
|
const resolveState = await this.onResolve();
|
||||||
...state,
|
if (resolveState) {
|
||||||
...((await this.onResolve()) ?? {}),
|
state = { ...state, ...resolveState };
|
||||||
};
|
}
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
console.error(err);
|
console.error("Controller resolve error:", error);
|
||||||
throw err;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.#resolved = true;
|
this.#resolved = true;
|
||||||
this.setState(state);
|
|
||||||
|
if (this.#destroyed === false) {
|
||||||
|
this.setState(state);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Destroys the controller and cleans up resources.
|
||||||
|
*/
|
||||||
async $destroy(): Promise<void> {
|
async $destroy(): Promise<void> {
|
||||||
for (const subscription of this.subscriptions.values()) {
|
this.#destroyed = true;
|
||||||
subscription.unsubscribe();
|
|
||||||
}
|
|
||||||
await this.onDestroy();
|
await this.onDestroy();
|
||||||
this.refs.destroy();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|--------------------------------------------------------------------------------
|
|--------------------------------------------------------------------------------
|
||||||
| Lifecycle Methods
|
| Lifecycle Hooks
|
||||||
|--------------------------------------------------------------------------------
|
|--------------------------------------------------------------------------------
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Method runs once per controller view lifecycle. This is where you should
|
* Called once when the controller is first initialized.
|
||||||
* subscribe to and return initial controller state. A component is kept in
|
|
||||||
* loading state until the initial resolve is completed.
|
|
||||||
*
|
|
||||||
* Once the initial resolve is completed the controller will not run the onInit
|
|
||||||
* method again unless the controller is destroyed and re-created.
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```ts
|
|
||||||
* async onInit() {
|
|
||||||
* return {
|
|
||||||
* foos: this.query(foos, {}, "foos")
|
|
||||||
* }
|
|
||||||
* }
|
|
||||||
* ```
|
|
||||||
*/
|
*/
|
||||||
async onInit(): Promise<Partial<TState> | void> {
|
async onInit(): Promise<Partial<TState> | void> {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Method runs every time the controller is resolved. This is where you should
|
* Called every time props change (including first mount).
|
||||||
* subscribe to and return state that is reflecting changes to the parent view
|
|
||||||
* properties.
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```ts
|
|
||||||
* async onResolve() {
|
|
||||||
* return {
|
|
||||||
* foos: this.query(foos, { tenantId: this.props.tenantId }, "foos")
|
|
||||||
* }
|
|
||||||
* }
|
|
||||||
* ```
|
|
||||||
*/
|
*/
|
||||||
async onResolve(): Promise<Partial<TState> | void> {
|
async onResolve(): Promise<Partial<TState> | void> {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Method runs when the controller parent view is destroyed.
|
* Called when the controller is destroyed.
|
||||||
*/
|
*/
|
||||||
async onDestroy(): Promise<void> {}
|
async onDestroy(): Promise<void> {}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|--------------------------------------------------------------------------------
|
|--------------------------------------------------------------------------------
|
||||||
| Query Methods
|
| State Management
|
||||||
|--------------------------------------------------------------------------------
|
|--------------------------------------------------------------------------------
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Executes a query on a given collection and returns the initial result. A
|
* Updates the controller state.
|
||||||
* subsequent internal subscription is also created, which automatically updates
|
|
||||||
* the controller state when changes are made to the data in which the query
|
|
||||||
* subscribes.
|
|
||||||
*
|
|
||||||
* @param collection - Collection to query against.
|
|
||||||
* @param query - Query to execute.
|
|
||||||
* @param stateKey - State key to assign the results to, or state handler method.
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```ts
|
|
||||||
* async onInit() {
|
|
||||||
* return {
|
|
||||||
* foo: await this.query(db.collection("foos"), { limit: 1 }, "foo")
|
|
||||||
* }
|
|
||||||
* }
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
async query<TCollection extends Collection<any>, TSchema = CollectionSchema<TCollection>, TStateKey = keyof TState>(
|
|
||||||
collection: TCollection,
|
|
||||||
query: QuerySingle,
|
|
||||||
next: TStateKey | ((document: TSchema | undefined) => Promise<Partial<TState>>),
|
|
||||||
): Promise<TSchema | undefined>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Executes a query on a given collection and returns the initial result. A
|
|
||||||
* subsequent internal subscription is also created, which automatically updates
|
|
||||||
* the controller state when changes are made to the data in which the query
|
|
||||||
* subscribes.
|
|
||||||
*
|
|
||||||
* @param collection - Collection to query against.
|
|
||||||
* @param query - Query to execute.
|
|
||||||
* @param next - State key to assign the results to, or state handler method.
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```ts
|
|
||||||
* async onInit() {
|
|
||||||
* return {
|
|
||||||
* foos: await this.query(db.collection("foos"), {}, "foos")
|
|
||||||
* }
|
|
||||||
* }
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
async query<TCollection extends Collection<any>, TSchema = CollectionSchema<TCollection>, TStateKey = keyof TState>(
|
|
||||||
collection: TCollection,
|
|
||||||
query: QueryMany,
|
|
||||||
next:
|
|
||||||
| TStateKey
|
|
||||||
| ((documents: TSchema[], changed: TSchema[], type: ChangeEvent["type"]) => Promise<Partial<TState>>),
|
|
||||||
): Promise<TSchema[]>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Executes a query on a given collection and returns the initial result. A
|
|
||||||
* subsequent internal subscription is also created, which automatically updates
|
|
||||||
* the controller state when changes are made to the data in which the query
|
|
||||||
* subscribes.
|
|
||||||
*
|
|
||||||
* @param collection - Collection to query against.
|
|
||||||
* @param query - Query to execute.
|
|
||||||
* @param stateKey - State key to assign the results to, or state handler method.
|
|
||||||
*/
|
|
||||||
async query<TCollection extends Collection<any>, TSchema = CollectionSchema<TCollection>, TStateKey = keyof TState>(
|
|
||||||
collection: TCollection,
|
|
||||||
query: Query,
|
|
||||||
next: TStateKey | ((...args: any[]) => Promise<Partial<TState>>),
|
|
||||||
): Promise<TSchema[] | TSchema | undefined> {
|
|
||||||
let resolved = false;
|
|
||||||
this.subscriptions.get(collection.name)?.unsubscribe();
|
|
||||||
return new Promise<CollectionSchema<TCollection>[] | CollectionSchema<TCollection> | undefined>((resolve) => {
|
|
||||||
const { where, ...options } = query;
|
|
||||||
this.subscriptions.set(
|
|
||||||
collection.name,
|
|
||||||
collection.subscribe(where, options, (...args: any[]) => {
|
|
||||||
if (this.#isStateKey(next)) {
|
|
||||||
if (resolved === true) {
|
|
||||||
this.setState(next, args[0]);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
(next as any)(...args).then(this.setState);
|
|
||||||
}
|
|
||||||
setTimeout(() => {
|
|
||||||
resolve(args[0]);
|
|
||||||
resolved = true;
|
|
||||||
}, 0);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Event Methods
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Consumes a subscription under a given event key that is unsubscribed
|
|
||||||
* automatically when the controller is unmounted.
|
|
||||||
*
|
|
||||||
* @param key - Unique identifier used to unsusbcribe duplicate subs.
|
|
||||||
* @param sub - Subscription to unsubscribe on controller unmount.
|
|
||||||
*/
|
|
||||||
subscribe(key: string, sub: { unsubscribe: () => void }): void {
|
|
||||||
this.subscriptions.get(key)?.unsubscribe();
|
|
||||||
this.subscriptions.set(key, sub);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| State Methods
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates the state of the controller and triggers a state update via the push
|
|
||||||
* state handler. This method will debounce state updates to prevent excessive
|
|
||||||
* state updates.
|
|
||||||
*
|
|
||||||
* @param key - State key to assign data to.
|
|
||||||
* @param value - State value to assign.
|
|
||||||
*/
|
*/
|
||||||
setState(state: Partial<TState>): void;
|
setState(state: Partial<TState>): void;
|
||||||
setState<K extends keyof TState>(key: K): (state: TState[K]) => void;
|
|
||||||
setState<K extends keyof TState>(key: K, value: TState[K]): void;
|
setState<K extends keyof TState>(key: K, value: TState[K]): void;
|
||||||
setState<K extends keyof TState>(...args: [K | TState, TState[K]?]): void | ((state: TState[K]) => void) {
|
setState<K extends keyof TState>(...args: [K | Partial<TState>, TState[K]?]): void {
|
||||||
|
if (this.#destroyed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const [target, value] = args;
|
const [target, value] = args;
|
||||||
|
|
||||||
if (this.#isStateKey(target) && args.length === 1) {
|
if (typeof target === "string") {
|
||||||
return (value: TState[K]) => {
|
this.state = { ...this.state, [target]: value };
|
||||||
this.setState(target, value);
|
} else {
|
||||||
};
|
this.state = { ...this.state, ...(target as Partial<TState>) };
|
||||||
}
|
}
|
||||||
|
|
||||||
this.state = this.#isStateKey(target)
|
this.#setState(this.state);
|
||||||
? {
|
this.#setLoading(false);
|
||||||
...this.state,
|
|
||||||
[target]: value,
|
|
||||||
}
|
|
||||||
: {
|
|
||||||
...this.state,
|
|
||||||
...(target as Partial<TState>),
|
|
||||||
};
|
|
||||||
|
|
||||||
if (this.#resolved === true) {
|
|
||||||
this.#debounce.run(() => {
|
|
||||||
this.setView(
|
|
||||||
this.view({
|
|
||||||
props: this.props,
|
|
||||||
state: this.state,
|
|
||||||
actions: this.toActions(),
|
|
||||||
refs: this.refs,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}, 0);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|--------------------------------------------------------------------------------
|
|--------------------------------------------------------------------------------
|
||||||
| Resolvers
|
| Actions
|
||||||
|--------------------------------------------------------------------------------
|
|--------------------------------------------------------------------------------
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns all the prototype methods defined on the controller as a list of
|
* Returns all public methods as bound actions.
|
||||||
* actions bound to the controller instance to be used in the view.
|
|
||||||
*
|
|
||||||
* @returns List of actions.
|
|
||||||
*/
|
*/
|
||||||
toActions(): Omit<this, ReservedPropertyMembers> {
|
toActions(): ControllerActions<this> {
|
||||||
const actions: any = {};
|
const actions: any = {};
|
||||||
for (const name of Object.getOwnPropertyNames(this.constructor.prototype)) {
|
const prototype = Object.getPrototypeOf(this);
|
||||||
if (name !== "constructor" && name !== "resolve") {
|
|
||||||
const action = (this as any)[name];
|
for (const name of Object.getOwnPropertyNames(prototype)) {
|
||||||
if (typeof action === "function") {
|
if (this.#isAction(name)) {
|
||||||
actions[name] = action.bind(this);
|
const method = (this as any)[name];
|
||||||
|
if (typeof method === "function") {
|
||||||
|
actions[name] = method.bind(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return actions;
|
return actions;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
#isAction(name: string): boolean {
|
||||||
|--------------------------------------------------------------------------------
|
return name !== "constructor" && !name.startsWith("$") && !name.startsWith("_") && !name.startsWith("#");
|
||||||
| Utilities
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
#isStateKey(key: unknown): key is keyof TState {
|
|
||||||
return typeof key === "string";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------------
|
||||||
|
| Hook
|
||||||
|
|--------------------------------------------------------------------------------
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* React hook for using a controller.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* function LoginView() {
|
||||||
|
* const [state, actions] = useController(LoginController);
|
||||||
|
*
|
||||||
|
* return (
|
||||||
|
* <button onClick={actions.login}>
|
||||||
|
* {state.authenticated ? "Logout" : "Login"}
|
||||||
|
* </button>
|
||||||
|
* );
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function useController<TController extends new (...args: any[]) => Controller<any, any>>(
|
||||||
|
ControllerClass: TController,
|
||||||
|
props?: InstanceType<TController>["props"],
|
||||||
|
): [InstanceType<TController>["state"], boolean, ControllerActions<InstanceType<TController>>] {
|
||||||
|
const [state, setState] = useState<any>({});
|
||||||
|
const [loading, setLoading] = useState<boolean>(true);
|
||||||
|
|
||||||
|
const controllerRef = useRef<InstanceType<TController> | null>(null);
|
||||||
|
const actionsRef = useRef<ControllerActions<InstanceType<TController>> | null>(null);
|
||||||
|
const propsRef = useRef(props);
|
||||||
|
|
||||||
|
// Resolve only once after creation
|
||||||
|
useMemo(() => {
|
||||||
|
const instance = (ControllerClass as any).make(setState, setLoading);
|
||||||
|
controllerRef.current = instance;
|
||||||
|
actionsRef.current = instance.toActions();
|
||||||
|
|
||||||
|
instance.$resolve(props || {});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
instance.$destroy();
|
||||||
|
};
|
||||||
|
}, [controllerRef]);
|
||||||
|
|
||||||
|
// Resolve on props change
|
||||||
|
useEffect(() => {
|
||||||
|
if (propsRef.current !== props) {
|
||||||
|
propsRef.current = props;
|
||||||
|
controllerRef.current?.$resolve(props || {});
|
||||||
|
}
|
||||||
|
}, [props]);
|
||||||
|
|
||||||
|
return [state, loading, actionsRef.current!];
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|--------------------------------------------------------------------------------
|
|--------------------------------------------------------------------------------
|
||||||
| Types
|
| Types
|
||||||
|--------------------------------------------------------------------------------
|
|--------------------------------------------------------------------------------
|
||||||
*/
|
*/
|
||||||
|
|
||||||
type Query = Where & SubscriptionOptions;
|
type ControllerActions<T> = {
|
||||||
|
[K in keyof T]: T[K] extends (...args: any[]) => any
|
||||||
type QuerySingle = Where & SubscribeToSingle;
|
? K extends `$${string}` | `_${string}` | `#${string}` | "constructor"
|
||||||
|
? never
|
||||||
type QueryMany = Where & SubscribeToMany;
|
: T[K]
|
||||||
|
: never;
|
||||||
type Where = {
|
|
||||||
where?: Record<string, unknown>;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
type CollectionSchema<TCollection extends Collection> = TCollection extends Collection<infer TSchema> ? TSchema : never;
|
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
export class Debounce {
|
|
||||||
#timeout?: number;
|
|
||||||
|
|
||||||
run(fn: (...args: any[]) => void, ms: number): void {
|
|
||||||
this.#clear();
|
|
||||||
this.#timeout = setTimeout(fn, ms);
|
|
||||||
}
|
|
||||||
|
|
||||||
#clear() {
|
|
||||||
if (this.#timeout !== undefined) {
|
|
||||||
clearTimeout(this.#timeout);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
const refs = new Map<string, HTMLElement>();
|
|
||||||
|
|
||||||
export class ControllerRefs {
|
|
||||||
#refs = new Map<string, HTMLElement>();
|
|
||||||
|
|
||||||
#forwarded: string[] = [];
|
|
||||||
|
|
||||||
set(name: string) {
|
|
||||||
return (element: HTMLElement | null) => {
|
|
||||||
if (element !== null) {
|
|
||||||
refs.set(name, element);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
forward(name: string) {
|
|
||||||
return (element: HTMLElement | null) => {
|
|
||||||
if (element !== null) {
|
|
||||||
refs.set(name, element);
|
|
||||||
this.#forwarded.push(name);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
get(name: string) {
|
|
||||||
const element = this.#refs.get(name) ?? refs.get(name);
|
|
||||||
if (element === undefined) {
|
|
||||||
throw new Error(`Reference Exception: ${name} is not defined.`);
|
|
||||||
}
|
|
||||||
return element;
|
|
||||||
}
|
|
||||||
|
|
||||||
async on(name: string, count = 0): Promise<HTMLElement | undefined> {
|
|
||||||
if (count > 20) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
const element = this.#refs.get(name) ?? refs.get(name);
|
|
||||||
if (element === undefined) {
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
||||||
return this.on(name, count + 1);
|
|
||||||
}
|
|
||||||
return element;
|
|
||||||
}
|
|
||||||
|
|
||||||
destroy() {
|
|
||||||
this.#forwarded.forEach((name) => {
|
|
||||||
refs.delete(name);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
import type React from "react";
|
|
||||||
import type { FunctionComponent } from "react";
|
|
||||||
|
|
||||||
import type { ControllerRefs } from "./refs.ts";
|
|
||||||
|
|
||||||
export type ReactComponent<TProps extends Unknown, TController extends ControllerClass> = FunctionComponent<{
|
|
||||||
props: TProps;
|
|
||||||
state: InstanceType<TController>["state"];
|
|
||||||
actions: Omit<InstanceType<TController>, ReservedPropertyMembers>;
|
|
||||||
refs: ControllerRefs;
|
|
||||||
component?: React.FC;
|
|
||||||
}>;
|
|
||||||
|
|
||||||
export type ControllerClass = {
|
|
||||||
new (state: any, pushState: any): any;
|
|
||||||
make(component: ReactComponent<any, any>, pushState: any): any;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ReservedPropertyMembers = "state" | "pushState" | "init" | "destroy" | "setNext" | "setState" | "toActions";
|
|
||||||
|
|
||||||
export type Unknown = Record<string, unknown>;
|
|
||||||
|
|
||||||
export type Empty = Record<string, never>;
|
|
||||||
6
apps/react/src/libraries/utils.ts
Normal file
6
apps/react/src/libraries/utils.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { type ClassValue, clsx } from "clsx";
|
||||||
|
import { twMerge } from "tailwind-merge";
|
||||||
|
|
||||||
|
export function cn(...inputs: ClassValue[]) {
|
||||||
|
return twMerge(clsx(inputs));
|
||||||
|
}
|
||||||
@@ -1,199 +0,0 @@
|
|||||||
import { deepEqual } from "fast-equals";
|
|
||||||
import React, { createElement, type FunctionComponent, memo, type PropsWithChildren, useEffect, useState } from "react";
|
|
||||||
|
|
||||||
import type { ControllerClass, ReactComponent, Unknown } from "./types.ts";
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Options
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
const options: Partial<ViewOptions<any>> = {
|
|
||||||
memoize: defaultMemoizeHandler,
|
|
||||||
};
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Factory
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
export function makeControllerView<TController extends ControllerClass, TProps extends Unknown>(
|
|
||||||
controller: TController,
|
|
||||||
component: ReactComponent<TProps, TController>,
|
|
||||||
options?: Partial<ViewOptions<TProps>>,
|
|
||||||
): FunctionComponent<TProps> {
|
|
||||||
const memoize = getMemoizeHandler(options?.memoize);
|
|
||||||
const render = {
|
|
||||||
loading: getLoadingComponent<TProps>(options),
|
|
||||||
error: getErrorComponent<TProps>(options),
|
|
||||||
};
|
|
||||||
|
|
||||||
const container: FunctionComponent<PropsWithChildren<TProps>> = (props: any) => {
|
|
||||||
const { error, view } = useView<TProps, TController>(controller, component, props);
|
|
||||||
if (view === undefined) {
|
|
||||||
return render.loading(props);
|
|
||||||
}
|
|
||||||
if (error !== undefined) {
|
|
||||||
return render.error({ ...props, error });
|
|
||||||
}
|
|
||||||
return view;
|
|
||||||
};
|
|
||||||
|
|
||||||
container.displayName = component.displayName = options?.name ?? `${controller.name}View`;
|
|
||||||
|
|
||||||
// ### Memoize
|
|
||||||
// By default run component through react memoization using stringify
|
|
||||||
// matching to determine changes to props.
|
|
||||||
|
|
||||||
if (memoize !== false) {
|
|
||||||
return memo(container, memoize);
|
|
||||||
}
|
|
||||||
|
|
||||||
return container;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Hooks
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
function useView<Props extends Unknown, Controller extends ControllerClass>(
|
|
||||||
instance: InstanceType<ControllerClass> | undefined,
|
|
||||||
component: ReactComponent<Props, Controller>,
|
|
||||||
props: any,
|
|
||||||
) {
|
|
||||||
const [view, setView] = useState();
|
|
||||||
|
|
||||||
const error = useController(instance, component, props, setView);
|
|
||||||
|
|
||||||
return { error, view };
|
|
||||||
}
|
|
||||||
|
|
||||||
function useController(controller: ControllerClass, component: any, props: any, setView: any) {
|
|
||||||
const [instance, setInstance] = useState<InstanceType<ControllerClass> | undefined>(undefined);
|
|
||||||
const error = useProps(instance, props);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const instance = controller.make(component, setView);
|
|
||||||
setInstance(instance);
|
|
||||||
return () => {
|
|
||||||
instance.$destroy();
|
|
||||||
};
|
|
||||||
}, [component, controller, setView]);
|
|
||||||
|
|
||||||
return error;
|
|
||||||
}
|
|
||||||
|
|
||||||
function useProps(controller: InstanceType<ControllerClass> | undefined, props: any) {
|
|
||||||
const [error, setError] = useState<Error | undefined>();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (controller === undefined) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let isMounted = true;
|
|
||||||
controller.$resolve(props).catch((error: Error) => {
|
|
||||||
if (isMounted === true) {
|
|
||||||
setError(error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return () => {
|
|
||||||
isMounted = false;
|
|
||||||
};
|
|
||||||
}, [controller, props]);
|
|
||||||
|
|
||||||
return error;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Components
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
export function setLoadingComponent(component: React.FC) {
|
|
||||||
options.loading = component;
|
|
||||||
}
|
|
||||||
|
|
||||||
function getLoadingComponent<TProps extends Unknown>({ loading }: Partial<ViewOptions<any>> = {}) {
|
|
||||||
const component = loading ?? options.loading;
|
|
||||||
if (component === undefined) {
|
|
||||||
return () => null;
|
|
||||||
}
|
|
||||||
return (props: TProps) => createElement(component, props);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function setErrorComponent(component: React.FC) {
|
|
||||||
options.error = component;
|
|
||||||
}
|
|
||||||
|
|
||||||
function getErrorComponent<TProps extends Unknown>({ error }: Partial<ViewOptions<any>> = {}) {
|
|
||||||
const component = error ?? options.loading;
|
|
||||||
if (component === undefined) {
|
|
||||||
return () => null;
|
|
||||||
}
|
|
||||||
return (props: TProps) => createElement(component, props);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Memoize
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
export function setMemoizeHandler(value: boolean | Memoize<any>) {
|
|
||||||
if (typeof value === "function") {
|
|
||||||
options.memoize = value;
|
|
||||||
} else if (value === false) {
|
|
||||||
options.memoize = false;
|
|
||||||
} else {
|
|
||||||
options.memoize = defaultMemoizeHandler;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function getMemoizeHandler(memoize?: ViewOptions<any>["memoize"]): false | Memoize<any> | undefined {
|
|
||||||
if (typeof memoize === "function") {
|
|
||||||
return memoize;
|
|
||||||
}
|
|
||||||
if (memoize !== false) {
|
|
||||||
return options.memoize;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Defaults
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
function defaultMemoizeHandler(prev: any, next: any): boolean {
|
|
||||||
if (prev.children !== undefined && next.children !== undefined) {
|
|
||||||
if (prev.children.type.type.displayName !== next.children.type.type.displayName) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return deepEqual(prev, next);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Types
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
export type ViewOptions<Props> = {
|
|
||||||
name?: string;
|
|
||||||
loading: React.FC<Props>;
|
|
||||||
error: React.FC<Props & { error: Error }>;
|
|
||||||
memoize: false | Memoize<Props>;
|
|
||||||
};
|
|
||||||
|
|
||||||
type Memoize<Props> = (prevProps: Readonly<Props>, nextProps: Readonly<Props>) => boolean;
|
|
||||||
|
|
||||||
type Readonly<T> = {
|
|
||||||
readonly [P in keyof T]: T[P];
|
|
||||||
};
|
|
||||||
@@ -4,6 +4,7 @@ import { createRouter, RouterProvider } from "@tanstack/react-router";
|
|||||||
import { StrictMode } from "react";
|
import { StrictMode } from "react";
|
||||||
import { createRoot } from "react-dom/client";
|
import { createRoot } from "react-dom/client";
|
||||||
|
|
||||||
|
import { ThemeProvider } from "./components/theme-provider.tsx";
|
||||||
import { routeTree } from "./routes.tsx";
|
import { routeTree } from "./routes.tsx";
|
||||||
|
|
||||||
const router = createRouter({ routeTree });
|
const router = createRouter({ routeTree });
|
||||||
@@ -14,8 +15,15 @@ declare module "@tanstack/react-router" {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
createRoot(document.getElementById("root")!).render(
|
const rootElement = document.getElementById("root");
|
||||||
|
if (rootElement === null) {
|
||||||
|
throw new Error("Failed to retrieve root element");
|
||||||
|
}
|
||||||
|
|
||||||
|
createRoot(rootElement).render(
|
||||||
<StrictMode>
|
<StrictMode>
|
||||||
<RouterProvider router={router} />
|
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
|
||||||
|
<RouterProvider router={router} />
|
||||||
|
</ThemeProvider>
|
||||||
</StrictMode>,
|
</StrictMode>,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,36 +1,30 @@
|
|||||||
import { createRootRoute, createRoute, Outlet } from "@tanstack/react-router";
|
import { createRootRoute, createRoute } from "@tanstack/react-router";
|
||||||
import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
|
|
||||||
|
|
||||||
import { CreateAccountView } from "./views/account/create.view.tsx";
|
import { AppView } from "./views/app.view.tsx";
|
||||||
import { TodosView } from "./views/todo/todos.view.tsx";
|
import { CallbackView } from "./views/auth/callback.view.tsx";
|
||||||
|
import { DashboardView } from "./views/dashboard/dashboard.view.tsx";
|
||||||
|
|
||||||
const rootRoute = createRootRoute({
|
const root = createRootRoute();
|
||||||
component: () => (
|
|
||||||
<>
|
const callback = createRoute({
|
||||||
<Outlet />
|
getParentRoute: () => root,
|
||||||
<TanStackRouterDevtools />
|
path: "/callback",
|
||||||
</>
|
component: CallbackView,
|
||||||
),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const homeRoute = createRoute({
|
const app = createRoute({
|
||||||
getParentRoute: () => rootRoute,
|
id: "app",
|
||||||
|
getParentRoute: () => root,
|
||||||
|
component: AppView,
|
||||||
|
});
|
||||||
|
|
||||||
|
const dashboard = createRoute({
|
||||||
|
getParentRoute: () => app,
|
||||||
path: "/",
|
path: "/",
|
||||||
component: function Index() {
|
component: DashboardView,
|
||||||
return <h3>Welcome Home!</h3>;
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const createAccountRoute = createRoute({
|
root.addChildren([app, callback]);
|
||||||
getParentRoute: () => rootRoute,
|
app.addChildren([dashboard]);
|
||||||
path: "/accounts",
|
|
||||||
component: CreateAccountView,
|
|
||||||
});
|
|
||||||
|
|
||||||
const todosRoute = createRoute({
|
export const routeTree = root;
|
||||||
getParentRoute: () => rootRoute,
|
|
||||||
path: "/todos",
|
|
||||||
component: TodosView,
|
|
||||||
});
|
|
||||||
|
|
||||||
export const routeTree = rootRoute.addChildren([homeRoute, createAccountRoute, todosRoute]);
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { account } from "@module/account/client";
|
||||||
import { makeClient } from "@platform/relay";
|
import { makeClient } from "@platform/relay";
|
||||||
|
|
||||||
import { HttpAdapter } from "../adapters/http.ts";
|
import { HttpAdapter } from "../adapters/http.ts";
|
||||||
@@ -9,7 +10,6 @@ export const api = makeClient(
|
|||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
account: (await import("@platform/spec/account/routes.ts")).routes,
|
account,
|
||||||
auth: (await import("@platform/spec/auth/routes.ts")).routes,
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
14
apps/react/src/services/zitadel.ts
Normal file
14
apps/react/src/services/zitadel.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { createZitadelAuth, type ZitadelConfig } from "@zitadel/react";
|
||||||
|
|
||||||
|
const config: ZitadelConfig = {
|
||||||
|
authority: "https://auth.valkyrjs.com",
|
||||||
|
client_id: "347982179092987909",
|
||||||
|
redirect_uri: "http://localhost:5173/callback",
|
||||||
|
post_logout_redirect_uri: "http://localhost:5173",
|
||||||
|
response_type: "code",
|
||||||
|
scope: "openid profile email",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const zitadel = createZitadelAuth(config);
|
||||||
|
|
||||||
|
export type User = NonNullable<Awaited<ReturnType<typeof zitadel.userManager.getUser>>>;
|
||||||
105
apps/react/src/theme.css
Normal file
105
apps/react/src/theme.css
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
body {
|
||||||
|
@apply overscroll-none bg-transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--font-sans: var(--font-inter);
|
||||||
|
--header-height: calc(var(--spacing) * 12 + 1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-scaled {
|
||||||
|
@media (min-width: 1024px) {
|
||||||
|
--radius: 0.6rem;
|
||||||
|
--text-lg: 1.05rem;
|
||||||
|
--text-base: 0.85rem;
|
||||||
|
--text-sm: 0.8rem;
|
||||||
|
--spacing: 0.222222rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-slot="card"] {
|
||||||
|
--spacing: 0.16rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-slot="select-trigger"],
|
||||||
|
[data-slot="toggle-group-item"] {
|
||||||
|
--spacing: 0.222222rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-default,
|
||||||
|
.theme-default-scaled {
|
||||||
|
--primary: var(--color-neutral-600);
|
||||||
|
--primary-foreground: var(--color-neutral-50);
|
||||||
|
|
||||||
|
@variant dark {
|
||||||
|
--primary: var(--color-neutral-500);
|
||||||
|
--primary-foreground: var(--color-neutral-50);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-blue,
|
||||||
|
.theme-blue-scaled {
|
||||||
|
--primary: var(--color-blue-600);
|
||||||
|
--primary-foreground: var(--color-blue-50);
|
||||||
|
|
||||||
|
@variant dark {
|
||||||
|
--primary: var(--color-blue-500);
|
||||||
|
--primary-foreground: var(--color-blue-50);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-green,
|
||||||
|
.theme-green-scaled {
|
||||||
|
--primary: var(--color-lime-600);
|
||||||
|
--primary-foreground: var(--color-lime-50);
|
||||||
|
|
||||||
|
@variant dark {
|
||||||
|
--primary: var(--color-lime-600);
|
||||||
|
--primary-foreground: var(--color-lime-50);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-amber,
|
||||||
|
.theme-amber-scaled {
|
||||||
|
--primary: var(--color-amber-600);
|
||||||
|
--primary-foreground: var(--color-amber-50);
|
||||||
|
|
||||||
|
@variant dark {
|
||||||
|
--primary: var(--color-amber-500);
|
||||||
|
--primary-foreground: var(--color-amber-50);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-mono,
|
||||||
|
.theme-mono-scaled {
|
||||||
|
--font-sans: var(--font-mono);
|
||||||
|
--primary: var(--color-neutral-600);
|
||||||
|
--primary-foreground: var(--color-neutral-50);
|
||||||
|
|
||||||
|
@variant dark {
|
||||||
|
--primary: var(--color-neutral-500);
|
||||||
|
--primary-foreground: var(--color-neutral-50);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rounded-xs,
|
||||||
|
.rounded-sm,
|
||||||
|
.rounded-md,
|
||||||
|
.rounded-lg,
|
||||||
|
.rounded-xl {
|
||||||
|
@apply !rounded-none;
|
||||||
|
border-radius: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.shadow-xs,
|
||||||
|
.shadow-sm,
|
||||||
|
.shadow-md,
|
||||||
|
.shadow-lg,
|
||||||
|
.shadow-xl {
|
||||||
|
@apply !shadow-none;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-slot="toggle-group"],
|
||||||
|
[data-slot="toggle-group-item"] {
|
||||||
|
@apply !rounded-none !shadow-none;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
import z from "zod";
|
|
||||||
|
|
||||||
import { Controller } from "../../libraries/controller.ts";
|
|
||||||
import { Form } from "../../libraries/form.ts";
|
|
||||||
import { api } from "../../services/api.ts";
|
|
||||||
|
|
||||||
const inputs = {
|
|
||||||
givenName: z.string(),
|
|
||||||
familyName: z.string(),
|
|
||||||
email: z.string(),
|
|
||||||
};
|
|
||||||
|
|
||||||
export class CreateController extends Controller<{
|
|
||||||
form: Form<typeof inputs>;
|
|
||||||
}> {
|
|
||||||
async onInit() {
|
|
||||||
return {
|
|
||||||
form: new Form(inputs).onSubmit(async ({ givenName, familyName, email }) => {
|
|
||||||
const response = await api.account.create({
|
|
||||||
body: {
|
|
||||||
name: {
|
|
||||||
given: givenName,
|
|
||||||
family: familyName,
|
|
||||||
},
|
|
||||||
email,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
if ("error" in response) {
|
|
||||||
console.log(response.error);
|
|
||||||
} else {
|
|
||||||
console.log(response.data);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { makeControllerView } from "../../libraries/view.ts";
|
|
||||||
import { CreateController } from "./create.controller.ts";
|
|
||||||
|
|
||||||
export const CreateAccountView = makeControllerView(CreateController, ({ state: { form } }) => {
|
|
||||||
return (
|
|
||||||
<form onSubmit={form.submit}>
|
|
||||||
<input placeholder="Given Name" {...form.register("givenName")} />
|
|
||||||
<input placeholder="Family Name" {...form.register("familyName")} />
|
|
||||||
<input placeholder="Email" {...form.register("email")} />
|
|
||||||
<button type="submit">Create</button>
|
|
||||||
</form>
|
|
||||||
);
|
|
||||||
});
|
|
||||||
25
apps/react/src/views/app.controller.ts
Normal file
25
apps/react/src/views/app.controller.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { Controller } from "../libraries/controller.ts";
|
||||||
|
import { zitadel } from "../services/zitadel.ts";
|
||||||
|
|
||||||
|
export class AppController extends Controller<{
|
||||||
|
authenticated: boolean;
|
||||||
|
}> {
|
||||||
|
async onInit() {
|
||||||
|
return {
|
||||||
|
authenticated: await this.#getAuthenticatedState(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async #getAuthenticatedState(): Promise<boolean> {
|
||||||
|
const user = await zitadel.userManager.getUser();
|
||||||
|
if (user === null) {
|
||||||
|
zitadel.authorize();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
signout() {
|
||||||
|
zitadel.signout();
|
||||||
|
}
|
||||||
|
}
|
||||||
40
apps/react/src/views/app.view.tsx
Normal file
40
apps/react/src/views/app.view.tsx
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import { Outlet } from "@tanstack/react-router";
|
||||||
|
|
||||||
|
import { AppSidebar } from "@/components/app-sidebar.tsx";
|
||||||
|
import { SiteHeader } from "@/components/site-header.tsx";
|
||||||
|
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar.tsx";
|
||||||
|
import { useController } from "@/libraries/controller.ts";
|
||||||
|
|
||||||
|
import { AppController } from "./app.controller.ts";
|
||||||
|
|
||||||
|
export function AppView() {
|
||||||
|
const [{ authenticated }, loading] = useController(AppController);
|
||||||
|
if (loading === true) {
|
||||||
|
return <div>Loading ...</div>;
|
||||||
|
}
|
||||||
|
if (authenticated === false) {
|
||||||
|
return <div>Unauthenticated</div>;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<SidebarProvider
|
||||||
|
style={
|
||||||
|
{
|
||||||
|
"--sidebar-width": "calc(var(--spacing) * 72)",
|
||||||
|
"--header-height": "calc(var(--spacing) * 12)",
|
||||||
|
} as React.CSSProperties
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<AppSidebar variant="inset" />
|
||||||
|
<SidebarInset>
|
||||||
|
<SiteHeader />
|
||||||
|
<div className="flex flex-1 flex-col">
|
||||||
|
<div className="@container/main flex flex-1 flex-col gap-2">
|
||||||
|
<div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
|
||||||
|
<Outlet />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</SidebarInset>
|
||||||
|
</SidebarProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
26
apps/react/src/views/auth/callback.view.tsx
Normal file
26
apps/react/src/views/auth/callback.view.tsx
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { useNavigate } from "@tanstack/react-router";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
|
||||||
|
import { zitadel } from "../../services/zitadel.ts";
|
||||||
|
|
||||||
|
export function CallbackView() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
useEffect(() => {
|
||||||
|
async function handleCallback() {
|
||||||
|
try {
|
||||||
|
const user = await zitadel.userManager.signinRedirectCallback();
|
||||||
|
if (user) {
|
||||||
|
navigate({ to: "/", replace: true });
|
||||||
|
} else {
|
||||||
|
navigate({ to: "/", replace: true });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Callback error", error);
|
||||||
|
navigate({ to: "/", replace: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
handleCallback();
|
||||||
|
}, [navigate]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
29
apps/react/src/views/auth/login.controller.ts
Normal file
29
apps/react/src/views/auth/login.controller.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import { Controller } from "../../libraries/controller.ts";
|
||||||
|
import { type User, zitadel } from "../../services/zitadel.ts";
|
||||||
|
|
||||||
|
export class LoginController extends Controller<{
|
||||||
|
user?: User;
|
||||||
|
}> {
|
||||||
|
async onInit() {
|
||||||
|
return {
|
||||||
|
user: await this.#getAuthenticationState(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async #getAuthenticationState(): Promise<User | undefined> {
|
||||||
|
return zitadel.userManager.getUser().then((user) => {
|
||||||
|
if (user === null) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return user;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
login() {
|
||||||
|
zitadel.authorize();
|
||||||
|
}
|
||||||
|
|
||||||
|
logout() {
|
||||||
|
zitadel.signout();
|
||||||
|
}
|
||||||
|
}
|
||||||
14
apps/react/src/views/auth/login.view.tsx
Normal file
14
apps/react/src/views/auth/login.view.tsx
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { useController } from "../../libraries/controller.ts";
|
||||||
|
import { LoginController } from "./login.controller.ts";
|
||||||
|
|
||||||
|
export function LoginView() {
|
||||||
|
const [{ user }, { login, logout }] = useController(LoginController);
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<button type="button" onClick={() => (user === undefined ? login() : logout())}>
|
||||||
|
{user === undefined ? "Login" : "Logout"}
|
||||||
|
</button>
|
||||||
|
{user !== undefined ? <pre>{JSON.stringify(user, null, 2)}</pre> : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
3
apps/react/src/views/dashboard/dashboard.view.tsx
Normal file
3
apps/react/src/views/dashboard/dashboard.view.tsx
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export function DashboardView() {
|
||||||
|
return <div>Dashboard</div>;
|
||||||
|
}
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
import z from "zod";
|
|
||||||
|
|
||||||
import { Controller } from "../../libraries/controller.ts";
|
|
||||||
import { Form } from "../../libraries/form.ts";
|
|
||||||
import { db } from "../../stores/database.ts";
|
|
||||||
import type { Todo } from "../../stores/todo.ts";
|
|
||||||
|
|
||||||
const inputs = {
|
|
||||||
name: z.string(),
|
|
||||||
};
|
|
||||||
|
|
||||||
export class TodosController extends Controller<{
|
|
||||||
form: Form<typeof inputs>;
|
|
||||||
todos: Todo[];
|
|
||||||
}> {
|
|
||||||
override async onInit() {
|
|
||||||
return {
|
|
||||||
form: new Form(inputs).onSubmit(async ({ name }) => {
|
|
||||||
db.collection("todos").insertOne({ name, items: [] });
|
|
||||||
}),
|
|
||||||
todos: await this.query(db.collection("todos"), { limit: 10 }, "todos"),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
remove(id: string) {
|
|
||||||
db.collection("todos").remove({ id });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
import { Link } from "@tanstack/react-router";
|
|
||||||
|
|
||||||
import { makeControllerView } from "../../libraries/view.ts";
|
|
||||||
import { TodosController } from "./todos.controller.ts";
|
|
||||||
|
|
||||||
export const TodosView = makeControllerView(
|
|
||||||
TodosController,
|
|
||||||
({ state: { form, todos }, actions: { remove } }) => {
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-gray-100 flex flex-col items-center py-10 px-4 font-sans">
|
|
||||||
<div className="w-full max-w-2xl space-y-8">
|
|
||||||
{/* Heading */}
|
|
||||||
<header className="text-center">
|
|
||||||
<h1 className="text-3xl font-semibold text-gray-800">Todo Lists</h1>
|
|
||||||
<p className="text-gray-500 mt-2">Create and manage your collections of tasks</p>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
{/* Create form */}
|
|
||||||
<form onSubmit={form.submit} className="flex gap-2 w-full">
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
placeholder="Enter todo list name..."
|
|
||||||
{...form.register("name")}
|
|
||||||
className="flex-1 px-3 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-gray-800 bg-gray-50"
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
className="px-5 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white font-medium transition"
|
|
||||||
>
|
|
||||||
Create
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
{/* Todo list output */}
|
|
||||||
<section>
|
|
||||||
<h2 className="text-lg font-medium text-gray-700 mb-4">Your Lists</h2>
|
|
||||||
{todos?.length > 0 ? (
|
|
||||||
<ul className="divide-y divide-gray-200 border border-gray-200 rounded-lg bg-white">
|
|
||||||
{todos.map((todo) => (
|
|
||||||
<li key={todo.id} className="flex items-center justify-between px-4 py-3">
|
|
||||||
{/* List name */}
|
|
||||||
<span className="text-gray-800 font-medium">{todo.name}</span>
|
|
||||||
|
|
||||||
{/* Actions */}
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Link
|
|
||||||
to="/todos/$id"
|
|
||||||
params={{ id: todo.id }}
|
|
||||||
className="px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-medium transition"
|
|
||||||
>
|
|
||||||
Open
|
|
||||||
</Link>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => remove(todo.id)}
|
|
||||||
className="px-3 py-1.5 rounded-lg bg-red-500 hover:bg-red-600 text-white text-sm font-medium transition"
|
|
||||||
>
|
|
||||||
Delete
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
) : (
|
|
||||||
<p className="text-gray-500 text-sm">No todo lists yet. Create one above!</p>
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
@@ -21,7 +21,14 @@
|
|||||||
"noUnusedParameters": true,
|
"noUnusedParameters": true,
|
||||||
// "erasableSyntaxOnly": true,
|
// "erasableSyntaxOnly": true,
|
||||||
"noFallthroughCasesInSwitch": true,
|
"noFallthroughCasesInSwitch": true,
|
||||||
"noUncheckedSideEffectImports": true
|
"noUncheckedSideEffectImports": true,
|
||||||
|
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"@/*": [
|
||||||
|
"./src/*"
|
||||||
|
]
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"include": ["src"]
|
"include": ["src"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,10 @@
|
|||||||
{
|
{
|
||||||
"files": [],
|
"files": [],
|
||||||
"references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
|
"references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }],
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"]
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
|
import path from "node:path"
|
||||||
import tailwindcss from "@tailwindcss/vite";
|
import tailwindcss from "@tailwindcss/vite";
|
||||||
import react from "@vitejs/plugin-react";
|
import react from "@vitejs/plugin-react";
|
||||||
import { defineConfig } from "vite";
|
import { defineConfig } from "vite";
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [react(), tailwindcss()],
|
plugins: [react(), tailwindcss()],
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
"@": path.resolve(__dirname, "./src"),
|
||||||
|
},
|
||||||
|
},
|
||||||
server: {
|
server: {
|
||||||
proxy: {
|
proxy: {
|
||||||
"/api/v1": {
|
"/api/v1": {
|
||||||
|
|||||||
10
deno.json
10
deno.json
@@ -4,8 +4,8 @@
|
|||||||
"workspace": [
|
"workspace": [
|
||||||
"api",
|
"api",
|
||||||
"apps/react",
|
"apps/react",
|
||||||
"modules/iam",
|
"modules/account",
|
||||||
"modules/workspace",
|
"modules/tenant",
|
||||||
"platform/cerbos",
|
"platform/cerbos",
|
||||||
"platform/config",
|
"platform/config",
|
||||||
"platform/database",
|
"platform/database",
|
||||||
@@ -19,16 +19,16 @@
|
|||||||
"platform/vault"
|
"platform/vault"
|
||||||
],
|
],
|
||||||
"tasks": {
|
"tasks": {
|
||||||
"start:api": {
|
"api": {
|
||||||
"command": "cd ./api && deno run start",
|
"command": "cd ./api && deno run start",
|
||||||
"description": "Start api server instance."
|
"description": "Start api server instance."
|
||||||
},
|
},
|
||||||
"start:react": {
|
"react": {
|
||||||
"command": "cd ./apps/react && deno run dev",
|
"command": "cd ./apps/react && deno run dev",
|
||||||
"description": "Start react application instance."
|
"description": "Start react application instance."
|
||||||
},
|
},
|
||||||
"check": {
|
"check": {
|
||||||
"command": "deno run -A npm:@biomejs/biome check --write ./api ./modules ./platform",
|
"command": "deno run -A npm:@biomejs/biome check --write ./api ./apps/react/src ./modules ./platform",
|
||||||
"description": "Format, lint, and organize imports of the entire project."
|
"description": "Format, lint, and organize imports of the entire project."
|
||||||
},
|
},
|
||||||
"test": {
|
"test": {
|
||||||
|
|||||||
4
modules/account/client.ts
Normal file
4
modules/account/client.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export const account = {
|
||||||
|
create: (await import("./routes/create/spec.ts")).default,
|
||||||
|
get: (await import("./routes/get/spec.ts")).default,
|
||||||
|
};
|
||||||
14
modules/account/package.json
Normal file
14
modules/account/package.json
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"name": "@module/account",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"exports": {
|
||||||
|
"./server": "./server.ts",
|
||||||
|
"./client": "./client.ts"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@platform/relay": "workspace:*",
|
||||||
|
"zod": "4.1.12"
|
||||||
|
}
|
||||||
|
}
|
||||||
5
modules/account/routes/create/handle.ts
Normal file
5
modules/account/routes/create/handle.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import route from "./spec.ts";
|
||||||
|
|
||||||
|
export default route.handle(async ({ body }) => {
|
||||||
|
console.log(body);
|
||||||
|
});
|
||||||
13
modules/account/routes/create/spec.ts
Normal file
13
modules/account/routes/create/spec.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { route } from "@platform/relay";
|
||||||
|
import z from "zod";
|
||||||
|
|
||||||
|
export default route.post("/api/v1/account").body(
|
||||||
|
z.strictObject({
|
||||||
|
tenantId: z.uuid().describe("Tenant identifier the account belongs to"),
|
||||||
|
userId: z.uuid().describe("User identifier the account belongs to"),
|
||||||
|
account: z.strictObject({
|
||||||
|
type: z.string().describe("Type of account being created"),
|
||||||
|
number: z.number().describe("Unique account identifier to create for the account"),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
5
modules/account/routes/get/handle.ts
Normal file
5
modules/account/routes/get/handle.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import route from "./spec.ts";
|
||||||
|
|
||||||
|
export default route.handle(async ({ params }) => {
|
||||||
|
console.log(params);
|
||||||
|
});
|
||||||
6
modules/account/routes/get/spec.ts
Normal file
6
modules/account/routes/get/spec.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { route } from "@platform/relay";
|
||||||
|
import z from "zod";
|
||||||
|
|
||||||
|
export default route.get("/api/v1/account/:number").params({
|
||||||
|
number: z.number().describe("Account number to retrieve"),
|
||||||
|
});
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
import { HTTP } from "@cerbos/http";
|
|
||||||
import { getEnvironmentVariable } from "@platform/config/environment.ts";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
export const cerbos = new HTTP(
|
|
||||||
getEnvironmentVariable({
|
|
||||||
key: "CERBOS_URL",
|
|
||||||
type: z.string(),
|
|
||||||
fallback: "http://localhost:3592",
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
adminCredentials: {
|
|
||||||
username: "cerbos",
|
|
||||||
password: "cerbosAdmin",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
# yaml-language-server: $schema=https://api.cerbos.dev/latest/cerbos/policy/v1/Policy.schema.json
|
|
||||||
# docs: https://docs.cerbos.dev/cerbos/latest/policies/resource_policies
|
|
||||||
|
|
||||||
apiVersion: api.cerbos.dev/v1
|
|
||||||
resourcePolicy:
|
|
||||||
resource: identity
|
|
||||||
version: default
|
|
||||||
rules:
|
|
||||||
|
|
||||||
# Admins can read any identity with limited fields
|
|
||||||
|
|
||||||
- actions: ["read", "update"]
|
|
||||||
effect: EFFECT_ALLOW
|
|
||||||
roles: ["admin"]
|
|
||||||
|
|
||||||
# Users can fully read, update, or delete their own identity
|
|
||||||
|
|
||||||
- actions: ["read", "update", "delete"]
|
|
||||||
effect: EFFECT_ALLOW
|
|
||||||
roles: ["user"]
|
|
||||||
condition:
|
|
||||||
match:
|
|
||||||
expr: request.resource.id == request.principal.id
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
# yaml-language-server: $schema=https://api.cerbos.dev/latest/cerbos/policy/v1/Policy.schema.json
|
|
||||||
# docs: https://docs.cerbos.dev/cerbos/latest/policies/resource_policies
|
|
||||||
|
|
||||||
apiVersion: api.cerbos.dev/v1
|
|
||||||
resourcePolicy:
|
|
||||||
resource: role
|
|
||||||
version: default
|
|
||||||
rules:
|
|
||||||
|
|
||||||
# Admin can manage roles
|
|
||||||
|
|
||||||
- actions: ["manage"]
|
|
||||||
effect: EFFECT_ALLOW
|
|
||||||
roles: ["super"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
/*
|
|
||||||
export const resources = new ResourceRegistry([
|
|
||||||
{
|
|
||||||
kind: "identity",
|
|
||||||
actions: ["read", "update", "delete"],
|
|
||||||
attr: {},
|
|
||||||
},
|
|
||||||
] as const);
|
|
||||||
|
|
||||||
export type Resource = typeof resources.$resource;
|
|
||||||
*/
|
|
||||||
@@ -1,163 +0,0 @@
|
|||||||
import { CheckResourcesResponse } from "@cerbos/core";
|
|
||||||
import { HttpAdapter, makeClient } from "@platform/relay";
|
|
||||||
|
|
||||||
import { config } from "./config.ts";
|
|
||||||
import checkResource from "./routes/access/check-resource/spec.ts";
|
|
||||||
import checkResources from "./routes/access/check-resources/spec.ts";
|
|
||||||
import isAllowed from "./routes/access/is-allowed/spec.ts";
|
|
||||||
import getById from "./routes/identities/get/spec.ts";
|
|
||||||
import loginByPassword from "./routes/login/code/spec.ts";
|
|
||||||
import loginByEmail from "./routes/login/email/spec.ts";
|
|
||||||
import loginByCode from "./routes/login/password/spec.ts";
|
|
||||||
import me from "./routes/me/spec.ts";
|
|
||||||
|
|
||||||
const adapter = new HttpAdapter({
|
|
||||||
url: config.url,
|
|
||||||
});
|
|
||||||
|
|
||||||
const access = makeClient(
|
|
||||||
{
|
|
||||||
adapter,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
isAllowed,
|
|
||||||
checkResource,
|
|
||||||
checkResources,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
export const identity = makeClient(
|
|
||||||
{
|
|
||||||
adapter,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* TODO ...
|
|
||||||
*/
|
|
||||||
getById,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TODO ...
|
|
||||||
*/
|
|
||||||
me,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TODO ...
|
|
||||||
*/
|
|
||||||
login: {
|
|
||||||
/**
|
|
||||||
* TODO ...
|
|
||||||
*/
|
|
||||||
email: loginByEmail,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TODO ...
|
|
||||||
*/
|
|
||||||
password: loginByPassword,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TODO ...
|
|
||||||
*/
|
|
||||||
code: loginByCode,
|
|
||||||
},
|
|
||||||
|
|
||||||
access: {
|
|
||||||
/**
|
|
||||||
* Check if a principal is allowed to perform an action on a resource.
|
|
||||||
*
|
|
||||||
* @param resource - Resource which we are validating.
|
|
||||||
* @param action - Action which we are validating.
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
*
|
|
||||||
* await access.isAllowed(
|
|
||||||
* {
|
|
||||||
* kind: "document",
|
|
||||||
* id: "1",
|
|
||||||
* attr: { owner: "user@example.com" },
|
|
||||||
* },
|
|
||||||
* "view"
|
|
||||||
* ); // => true
|
|
||||||
*/
|
|
||||||
isAllowed: async (resource: Resource, action: string) => {
|
|
||||||
const response = await access.isAllowed({ body: { resource, action } });
|
|
||||||
if ("error" in response) {
|
|
||||||
throw response.error;
|
|
||||||
}
|
|
||||||
return response.data;
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check a principal's permissions on a resource.
|
|
||||||
*
|
|
||||||
* @param resource - Resource which we are validating.
|
|
||||||
* @param actions - Actions which we are validating.
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
*
|
|
||||||
* const decision = await access.checkResource(
|
|
||||||
* {
|
|
||||||
* kind: "document",
|
|
||||||
* id: "1",
|
|
||||||
* attr: { owner: "user@example.com" },
|
|
||||||
* },
|
|
||||||
* ["view", "edit"],
|
|
||||||
* );
|
|
||||||
*
|
|
||||||
* decision.isAllowed("view"); // => true
|
|
||||||
*/
|
|
||||||
checkResource: async (resource: Resource, actions: string[]) => {
|
|
||||||
const response = await access.checkResource({ body: { resource, actions } });
|
|
||||||
if ("error" in response) {
|
|
||||||
throw response.error;
|
|
||||||
}
|
|
||||||
return new CheckResourcesResponse(response.data);
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check a principal's permissions on a set of resources.
|
|
||||||
*
|
|
||||||
* @param resources - Resources which we are validating.
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
*
|
|
||||||
* const decision = await access.checkResources([
|
|
||||||
* {
|
|
||||||
* resource: {
|
|
||||||
* kind: "document",
|
|
||||||
* id: "1",
|
|
||||||
* attr: { owner: "user@example.com" },
|
|
||||||
* },
|
|
||||||
* actions: ["view", "edit"],
|
|
||||||
* },
|
|
||||||
* {
|
|
||||||
* resource: {
|
|
||||||
* kind: "image",
|
|
||||||
* id: "1",
|
|
||||||
* attr: { owner: "user@example.com" },
|
|
||||||
* },
|
|
||||||
* actions: ["delete"],
|
|
||||||
* },
|
|
||||||
* ]);
|
|
||||||
*
|
|
||||||
* decision.isAllowed({
|
|
||||||
* resource: { kind: "document", id: "1" },
|
|
||||||
* action: "view",
|
|
||||||
* }); // => true
|
|
||||||
*/
|
|
||||||
checkResources: async (resources: { resource: Resource; actions: string[] }[]) => {
|
|
||||||
const response = await access.checkResources({ body: resources });
|
|
||||||
if ("error" in response) {
|
|
||||||
throw response.error;
|
|
||||||
}
|
|
||||||
return new CheckResourcesResponse(response.data);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
type Resource = {
|
|
||||||
kind: string;
|
|
||||||
id: string;
|
|
||||||
attr: Record<string, any>;
|
|
||||||
};
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
import { getEnvironmentVariable } from "@platform/config/environment.ts";
|
|
||||||
import type { SerializeOptions } from "cookie";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
export const config = {
|
|
||||||
url: getEnvironmentVariable({
|
|
||||||
key: "IDENTITY_SERVICE_URL",
|
|
||||||
type: z.url(),
|
|
||||||
fallback: "http://localhost:8370",
|
|
||||||
}),
|
|
||||||
internal: {
|
|
||||||
privateKey: getEnvironmentVariable({
|
|
||||||
key: "IDENTITY_PRIVATE_KEY",
|
|
||||||
type: z.string(),
|
|
||||||
fallback:
|
|
||||||
"-----BEGIN PRIVATE KEY-----\n" +
|
|
||||||
"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg2WYKMJZUWff5XOWC\n" +
|
|
||||||
"XGuU+wmsRzhQGEIzfUoL6rrGoaehRANCAATCpiGiFQxTA76EIVG0cBbj+AFt6BuJ\n" +
|
|
||||||
"t4q+zoInPUzkChCdwI+XfAYokrZwBjcyRGluC02HaN3cptrmjYSGSMSx\n" +
|
|
||||||
"-----END PRIVATE KEY-----",
|
|
||||||
}),
|
|
||||||
publicKey: getEnvironmentVariable({
|
|
||||||
key: "IDENTITY_PUBLIC_KEY",
|
|
||||||
type: z.string(),
|
|
||||||
fallback:
|
|
||||||
"-----BEGIN PUBLIC KEY-----\n" +
|
|
||||||
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEwqYhohUMUwO+hCFRtHAW4/gBbegb\n" +
|
|
||||||
"ibeKvs6CJz1M5AoQncCPl3wGKJK2cAY3MkRpbgtNh2jd3Kba5o2EhkjEsQ==\n" +
|
|
||||||
"-----END PUBLIC KEY-----",
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
cookie: (maxAge: number) =>
|
|
||||||
({
|
|
||||||
httpOnly: true,
|
|
||||||
secure: getEnvironmentVariable({
|
|
||||||
key: "AUTH_COOKIE_SECURE",
|
|
||||||
type: z.coerce.boolean(),
|
|
||||||
fallback: "false",
|
|
||||||
}), // Set to true for HTTPS in production
|
|
||||||
maxAge,
|
|
||||||
path: "/",
|
|
||||||
sameSite: "strict",
|
|
||||||
}) satisfies SerializeOptions,
|
|
||||||
};
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
import { makeDocumentParser } from "@platform/database/utilities.ts";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
export enum PrincipalTypeId {
|
|
||||||
User = 1,
|
|
||||||
Group = 2,
|
|
||||||
Other = 99,
|
|
||||||
}
|
|
||||||
|
|
||||||
export const PRINCIPAL_TYPE_NAMES = {
|
|
||||||
[PrincipalTypeId.User]: "User",
|
|
||||||
[PrincipalTypeId.Group]: "Group",
|
|
||||||
[PrincipalTypeId.Other]: "Other",
|
|
||||||
};
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Schema
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
export const PrincipalSchema = z.object({
|
|
||||||
id: z.string(),
|
|
||||||
type: z.strictObject({
|
|
||||||
id: z.enum(PrincipalTypeId),
|
|
||||||
name: z.string(),
|
|
||||||
}),
|
|
||||||
roles: z.array(z.string()),
|
|
||||||
attr: z.record(z.string(), z.any()),
|
|
||||||
});
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Parsers
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
export const parsePrincipal = makeDocumentParser(PrincipalSchema);
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Types
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
export type Principal = z.infer<typeof PrincipalSchema>;
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
import z from "zod";
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Schema
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
export const SessionSchema = z.object({
|
|
||||||
id: z.string(),
|
|
||||||
userId: z.string(),
|
|
||||||
token: z.string(),
|
|
||||||
ipAddress: z.string().nullable().optional(),
|
|
||||||
userAgent: z.string().nullable().optional(),
|
|
||||||
createdAt: z.coerce.date(),
|
|
||||||
updatedAt: z.coerce.date(),
|
|
||||||
expiresAt: z.coerce.date(),
|
|
||||||
});
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Types
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
export type Session = z.infer<typeof SessionSchema>;
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "@modules/identity",
|
|
||||||
"version": "0.0.0",
|
|
||||||
"private": true,
|
|
||||||
"type": "module",
|
|
||||||
"exports": {
|
|
||||||
"./client.ts": "./client.ts",
|
|
||||||
"./server.ts": "./server.ts",
|
|
||||||
"./types.ts": "./types.ts"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@cerbos/core": "0.24.1",
|
|
||||||
"@cerbos/http": "0.23.1",
|
|
||||||
"@platform/config": "workspace:*",
|
|
||||||
"@platform/logger": "workspace:*",
|
|
||||||
"@platform/relay": "workspace:*",
|
|
||||||
"@platform/storage": "workspace:*",
|
|
||||||
"@platform/vault": "workspace:*",
|
|
||||||
"better-auth": "1.3.16",
|
|
||||||
"cookie": "1.0.2",
|
|
||||||
"zod": "4.1.11"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
import { cerbos } from "../../../cerbos/client.ts";
|
|
||||||
import route from "./spec.ts";
|
|
||||||
|
|
||||||
export default route.access("session").handle(async ({ body: { resource, actions } }, { principal }) => {
|
|
||||||
return cerbos.checkResource({ principal, resource, actions });
|
|
||||||
});
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import { route } from "@platform/relay";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
export default route
|
|
||||||
.post("/api/v1/identity/access/check-resource")
|
|
||||||
.body(
|
|
||||||
z.strictObject({
|
|
||||||
resource: z.strictObject({
|
|
||||||
kind: z.string(),
|
|
||||||
id: z.string(),
|
|
||||||
attr: z.record(z.string(), z.any()),
|
|
||||||
}),
|
|
||||||
actions: z.array(z.string()),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.response(z.any());
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
import { cerbos } from "../../../cerbos/client.ts";
|
|
||||||
import route from "./spec.ts";
|
|
||||||
|
|
||||||
export default route.access("session").handle(async ({ body: resources }, { principal }) => {
|
|
||||||
return cerbos.checkResources({ principal, resources });
|
|
||||||
});
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
import { route } from "@platform/relay";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
export default route
|
|
||||||
.post("/api/v1/identity/access/check-resources")
|
|
||||||
.body(
|
|
||||||
z.array(
|
|
||||||
z.strictObject({
|
|
||||||
resource: z.strictObject({
|
|
||||||
kind: z.string(),
|
|
||||||
id: z.string(),
|
|
||||||
attr: z.record(z.string(), z.any()),
|
|
||||||
}),
|
|
||||||
actions: z.array(z.string()),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.response(z.any());
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
import { cerbos } from "../../../cerbos/client.ts";
|
|
||||||
import route from "./spec.ts";
|
|
||||||
|
|
||||||
export default route.access("session").handle(async ({ body: { resource, action } }, { principal }) => {
|
|
||||||
return cerbos.isAllowed({ principal, resource, action });
|
|
||||||
});
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import { route } from "@platform/relay";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
export default route
|
|
||||||
.post("/api/v1/identity/access/is-allowed")
|
|
||||||
.body(
|
|
||||||
z.strictObject({
|
|
||||||
resource: z.strictObject({
|
|
||||||
kind: z.string(),
|
|
||||||
id: z.string(),
|
|
||||||
attr: z.record(z.string(), z.any()),
|
|
||||||
}),
|
|
||||||
action: z.string(),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.response(z.boolean());
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import { ForbiddenError, NotFoundError } from "@platform/relay";
|
|
||||||
|
|
||||||
import { getPrincipalById } from "../../../services/database.ts";
|
|
||||||
import route from "./spec.ts";
|
|
||||||
|
|
||||||
export default route.access("session").handle(async ({ params: { id } }, { access }) => {
|
|
||||||
const principal = await getPrincipalById(id);
|
|
||||||
if (principal === undefined) {
|
|
||||||
return new NotFoundError("Identity does not exist, or has been removed.");
|
|
||||||
}
|
|
||||||
const decision = await access.isAllowed({ kind: "identity", id, attr: {} }, "read");
|
|
||||||
if (decision === false) {
|
|
||||||
return new ForbiddenError("You do not have permission to view this identity.");
|
|
||||||
}
|
|
||||||
return principal;
|
|
||||||
});
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
import { ForbiddenError, NotFoundError, route, UnauthorizedError } from "@platform/relay";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
export default route
|
|
||||||
.get("/api/v1/identity/:id")
|
|
||||||
.params({
|
|
||||||
id: z.string(),
|
|
||||||
})
|
|
||||||
.errors([UnauthorizedError, ForbiddenError, NotFoundError])
|
|
||||||
.response(z.any());
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
import { ForbiddenError, NotFoundError } from "@platform/relay";
|
|
||||||
|
|
||||||
import { getPrincipalById, setPrincipalAttributesById } from "../../../services/database.ts";
|
|
||||||
import route from "./spec.ts";
|
|
||||||
|
|
||||||
export default route.access("session").handle(async ({ params: { id }, body: ops }, { access }) => {
|
|
||||||
const principal = await getPrincipalById(id);
|
|
||||||
if (principal === undefined) {
|
|
||||||
return new NotFoundError();
|
|
||||||
}
|
|
||||||
const decision = await access.isAllowed({ kind: "identity", id: principal.id, attr: principal.attr }, "update");
|
|
||||||
if (decision === false) {
|
|
||||||
return new ForbiddenError("You do not have permission to update this identity.");
|
|
||||||
}
|
|
||||||
const attr = principal.attr;
|
|
||||||
for (const op of ops) {
|
|
||||||
switch (op.type) {
|
|
||||||
case "add": {
|
|
||||||
attr[op.key] = op.value;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "push": {
|
|
||||||
if (attr[op.key] === undefined) {
|
|
||||||
attr[op.key] = op.values;
|
|
||||||
} else {
|
|
||||||
attr[op.key] = [...attr[op.key], ...op.values];
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "pop": {
|
|
||||||
if (Array.isArray(attr[op.key])) {
|
|
||||||
attr[op.key] = attr[op.key].filter((value: any) => op.values.includes(value) === false);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "remove": {
|
|
||||||
delete attr[op.key];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await setPrincipalAttributesById(id, attr);
|
|
||||||
});
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
import { ForbiddenError, NotFoundError, route, UnauthorizedError } from "@platform/relay";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
export default route
|
|
||||||
.put("/api/v1/identity/:id")
|
|
||||||
.params({
|
|
||||||
id: z.string(),
|
|
||||||
})
|
|
||||||
.body(
|
|
||||||
z.array(
|
|
||||||
z.union([
|
|
||||||
z.strictObject({
|
|
||||||
type: z.union([z.literal("add")]),
|
|
||||||
key: z.string(),
|
|
||||||
value: z.any(),
|
|
||||||
}),
|
|
||||||
z.strictObject({
|
|
||||||
type: z.union([z.literal("push"), z.literal("pop")]),
|
|
||||||
key: z.string(),
|
|
||||||
values: z.array(z.any()),
|
|
||||||
}),
|
|
||||||
z.strictObject({
|
|
||||||
type: z.union([z.literal("remove")]),
|
|
||||||
key: z.string(),
|
|
||||||
}),
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.errors([UnauthorizedError, ForbiddenError, NotFoundError]);
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import { NotFoundError } from "@platform/relay";
|
|
||||||
|
|
||||||
import { auth } from "../../../services/auth.ts";
|
|
||||||
import { logger } from "../../../services/logger.ts";
|
|
||||||
import route from "./spec.ts";
|
|
||||||
|
|
||||||
export default route.access("public").handle(async ({ body: { email, otp } }) => {
|
|
||||||
const response = await auth.api.signInEmailOTP({ body: { email, otp }, asResponse: true, returnHeaders: true });
|
|
||||||
if (response.status !== 200) {
|
|
||||||
logger.error("OTP Signin Failed", await response.json());
|
|
||||||
return new NotFoundError();
|
|
||||||
}
|
|
||||||
return new Response(null, {
|
|
||||||
headers: response.headers,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { route } from "@platform/relay";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
export default route
|
|
||||||
.post("/api/v1/identity/login/code")
|
|
||||||
.body(
|
|
||||||
z.strictObject({
|
|
||||||
email: z.string(),
|
|
||||||
otp: z.string(),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.query({
|
|
||||||
next: z.string().optional(),
|
|
||||||
});
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { auth } from "../../../services/auth.ts";
|
|
||||||
import { logger } from "../../../services/logger.ts";
|
|
||||||
import route from "./spec.ts";
|
|
||||||
|
|
||||||
export default route.access("public").handle(async ({ body: { email } }) => {
|
|
||||||
const response = await auth.api.sendVerificationOTP({ body: { email, type: "sign-in" } });
|
|
||||||
if (response.success === false) {
|
|
||||||
logger.info({
|
|
||||||
type: "auth:passwordless",
|
|
||||||
message: "OTP Email verification failed.",
|
|
||||||
received: email,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
import { route } from "@platform/relay";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
export default route.post("/api/v1/identity/login/email").body(
|
|
||||||
z.object({
|
|
||||||
email: z.email(),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
import { logger } from "@platform/logger";
|
|
||||||
import { BadRequestError } from "@platform/relay";
|
|
||||||
import cookie from "cookie";
|
|
||||||
|
|
||||||
import { auth } from "../../../auth.ts";
|
|
||||||
import { config } from "../../../config.ts";
|
|
||||||
import { password } from "../../../crypto/password.ts";
|
|
||||||
import { getPasswordStrategyByAlias } from "../../../database.ts";
|
|
||||||
import route from "./spec.ts";
|
|
||||||
|
|
||||||
export default route.access("public").handle(async ({ body: { alias, password: userPassword } }) => {
|
|
||||||
const strategy = await getPasswordStrategyByAlias(alias);
|
|
||||||
if (strategy === undefined) {
|
|
||||||
return logger.info({
|
|
||||||
type: "auth:password",
|
|
||||||
message: "Failed to get account with 'password' strategy.",
|
|
||||||
alias,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const isValidPassword = await password.verify(userPassword, strategy.password);
|
|
||||||
if (isValidPassword === false) {
|
|
||||||
return new BadRequestError("Invalid email/password provided.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return new Response(null, {
|
|
||||||
status: 204,
|
|
||||||
headers: {
|
|
||||||
"set-cookie": cookie.serialize(
|
|
||||||
"token",
|
|
||||||
await auth.generate({ id: strategy.accountId }, "1 week"),
|
|
||||||
config.cookie(1000 * 60 * 60 * 24 * 7),
|
|
||||||
),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
import { route } from "@platform/relay";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
export default route.post("/api/v1/identities/login/password").body(
|
|
||||||
z.object({
|
|
||||||
alias: z.string(),
|
|
||||||
password: z.string(),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
import route from "./spec.ts";
|
|
||||||
|
|
||||||
export default route.access("public").handle(async () => {
|
|
||||||
// const code = await Passwordless.createCode({ tenantId: "public", email });
|
|
||||||
// if (code.status !== "OK") {
|
|
||||||
// return logger.info({
|
|
||||||
// type: "auth:passwordless",
|
|
||||||
// message: "Create code failed.",
|
|
||||||
// received: email,
|
|
||||||
// });
|
|
||||||
// }
|
|
||||||
// logger.info({
|
|
||||||
// type: "auth:passwordless",
|
|
||||||
// data: {
|
|
||||||
// deviceId: code.deviceId,
|
|
||||||
// preAuthSessionId: code.preAuthSessionId,
|
|
||||||
// userInputCode: code.userInputCode,
|
|
||||||
// },
|
|
||||||
// });
|
|
||||||
// const response = await Passwordless.consumeCode({
|
|
||||||
// tenantId: "public",
|
|
||||||
// preAuthSessionId: code.preAuthSessionId,
|
|
||||||
// deviceId: code.deviceId,
|
|
||||||
// userInputCode: code.userInputCode,
|
|
||||||
// });
|
|
||||||
// if (response.status !== "OK") {
|
|
||||||
// return new NotFoundError();
|
|
||||||
// }
|
|
||||||
// logger.info({
|
|
||||||
// type: "code:claimed",
|
|
||||||
// session: true,
|
|
||||||
// message: "Identity resolved",
|
|
||||||
// user: response.user.toJson(),
|
|
||||||
// });
|
|
||||||
// return new Response(null, {
|
|
||||||
// status: 200,
|
|
||||||
// headers: await getSessionHeaders("public", response.recipeUserId),
|
|
||||||
// });
|
|
||||||
});
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
import { route } from "@platform/relay";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
export default route.post("/api/v1/identities/login/sudo").body(
|
|
||||||
z.object({
|
|
||||||
email: z.email(),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
import route from "./spec.ts";
|
|
||||||
|
|
||||||
export default route.access("session").handle(async ({ principal }) => {
|
|
||||||
return principal;
|
|
||||||
});
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
import { NotFoundError, route, UnauthorizedError } from "@platform/relay";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
export default route.get("/api/v1/identity/me").errors([UnauthorizedError, NotFoundError]).response(z.any());
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
import { ForbiddenError, NotFoundError } from "@platform/relay";
|
|
||||||
|
|
||||||
import { getPrincipalById, setPrincipalRolesById } from "../../services/database.ts";
|
|
||||||
import route from "./spec.ts";
|
|
||||||
|
|
||||||
export default route.access("session").handle(async ({ params: { id }, body: ops }, { access }) => {
|
|
||||||
const principal = await getPrincipalById(id);
|
|
||||||
if (principal === undefined) {
|
|
||||||
return new NotFoundError();
|
|
||||||
}
|
|
||||||
const decision = await access.isAllowed({ kind: "role", id: principal.id, attr: principal.attr }, "manage");
|
|
||||||
if (decision === false) {
|
|
||||||
return new ForbiddenError("You do not have permission to modify roles for this identity.");
|
|
||||||
}
|
|
||||||
const roles: Set<string> = new Set(principal.roles);
|
|
||||||
for (const op of ops) {
|
|
||||||
switch (op.type) {
|
|
||||||
case "add": {
|
|
||||||
for (const role of op.roles) {
|
|
||||||
roles.add(role);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "remove": {
|
|
||||||
for (const role of op.roles) {
|
|
||||||
roles.delete(role);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await setPrincipalRolesById(id, Array.from(roles));
|
|
||||||
});
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
import { ForbiddenError, NotFoundError, route, UnauthorizedError } from "@platform/relay";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
export default route
|
|
||||||
.put("/api/v1/identity/:id/roles")
|
|
||||||
.params({
|
|
||||||
id: z.string(),
|
|
||||||
})
|
|
||||||
.body(
|
|
||||||
z.array(
|
|
||||||
z.union([
|
|
||||||
z.strictObject({
|
|
||||||
type: z.union([z.literal("add"), z.literal("remove")]),
|
|
||||||
roles: z.array(z.any()),
|
|
||||||
}),
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.errors([UnauthorizedError, ForbiddenError, NotFoundError]);
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
import { NotFoundError } from "@platform/relay";
|
|
||||||
|
|
||||||
import { config } from "../../../config.ts";
|
|
||||||
import { getPrincipalByUserId } from "../../../services/database.ts";
|
|
||||||
import { getSessionByRequestHeader } from "../../../services/session.ts";
|
|
||||||
import route from "./spec.ts";
|
|
||||||
|
|
||||||
export default route.access(["internal:public", config.internal.privateKey]).handle(async ({ request }) => {
|
|
||||||
const session = await getSessionByRequestHeader(request.headers);
|
|
||||||
if (session === undefined) {
|
|
||||||
return new NotFoundError();
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
session,
|
|
||||||
principal: await getPrincipalByUserId(session.userId),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import { route } from "@platform/relay";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
import { PrincipalSchema } from "../../../models/principal.ts";
|
|
||||||
import { SessionSchema } from "../../../models/session.ts";
|
|
||||||
|
|
||||||
export default route.get("/api/v1/identity/session").response(
|
|
||||||
z.object({
|
|
||||||
session: SessionSchema,
|
|
||||||
principal: PrincipalSchema,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
import { HttpAdapter, makeClient } from "@platform/relay";
|
|
||||||
|
|
||||||
import { config } from "./config.ts";
|
|
||||||
import resolve from "./routes/session/resolve/spec.ts";
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Internal Session Resolver
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
const identity = makeClient(
|
|
||||||
{
|
|
||||||
adapter: new HttpAdapter({
|
|
||||||
url: config.url,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
resolve: resolve.crypto({
|
|
||||||
publicKey: config.internal.publicKey,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
export async function getPrincipalSession(payload: { headers: Headers }) {
|
|
||||||
const response = await identity.resolve(payload);
|
|
||||||
if ("data" in response) {
|
|
||||||
return response.data;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Server Exports
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
export * from "./services/session.ts";
|
|
||||||
export * from "./types.ts";
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Module Server
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
export default {
|
|
||||||
routes: [
|
|
||||||
(await import("./routes/identities/get/handle.ts")).default,
|
|
||||||
(await import("./routes/identities/update/handle.ts")).default,
|
|
||||||
(await import("./routes/login/code/handle.ts")).default,
|
|
||||||
(await import("./routes/login/email/handle.ts")).default,
|
|
||||||
// (await import("./routes/login/password/handle.ts")).default,
|
|
||||||
(await import("./routes/login/sudo/handle.ts")).default,
|
|
||||||
(await import("./routes/me/handle.ts")).default,
|
|
||||||
(await import("./routes/roles/handle.ts")).default,
|
|
||||||
(await import("./routes/session/resolve/handle.ts")).default,
|
|
||||||
(await import("./routes/access/is-allowed/handle.ts")).default,
|
|
||||||
(await import("./routes/access/check-resource/handle.ts")).default,
|
|
||||||
(await import("./routes/access/check-resources/handle.ts")).default,
|
|
||||||
],
|
|
||||||
};
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
import { logger } from "@platform/logger";
|
|
||||||
import { betterAuth } from "better-auth";
|
|
||||||
import { mongodbAdapter } from "better-auth/adapters/mongodb";
|
|
||||||
import { emailOTP } from "better-auth/plugins";
|
|
||||||
|
|
||||||
import { db } from "./database.ts";
|
|
||||||
|
|
||||||
export const auth = betterAuth({
|
|
||||||
database: mongodbAdapter(db.db),
|
|
||||||
session: {
|
|
||||||
cookieCache: {
|
|
||||||
enabled: true,
|
|
||||||
maxAge: 5 * 60, // Cache duration in seconds
|
|
||||||
},
|
|
||||||
},
|
|
||||||
plugins: [
|
|
||||||
emailOTP({
|
|
||||||
async sendVerificationOTP({ email, otp, type }) {
|
|
||||||
if (type === "sign-in") {
|
|
||||||
logger.info({ email, otp, type });
|
|
||||||
} else if (type === "email-verification") {
|
|
||||||
// Send the OTP for email verification
|
|
||||||
} else {
|
|
||||||
// Send the OTP for password reset
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
import { getDatabaseAccessor } from "@platform/database/accessor.ts";
|
|
||||||
|
|
||||||
import {
|
|
||||||
PRINCIPAL_TYPE_NAMES,
|
|
||||||
type Principal,
|
|
||||||
PrincipalSchema,
|
|
||||||
PrincipalTypeId,
|
|
||||||
parsePrincipal,
|
|
||||||
} from "../models/principal.ts";
|
|
||||||
|
|
||||||
export const db = getDatabaseAccessor<{
|
|
||||||
principal: Principal;
|
|
||||||
}>("auth");
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
| Methods
|
|
||||||
|--------------------------------------------------------------------------------
|
|
||||||
*/
|
|
||||||
|
|
||||||
export async function getPrincipalById(id: string): Promise<Principal | undefined> {
|
|
||||||
return db
|
|
||||||
.collection("principal")
|
|
||||||
.findOne({ id })
|
|
||||||
.then((value) => parsePrincipal(value));
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setPrincipalRolesById(id: string, roles: string[]): Promise<void> {
|
|
||||||
await db.collection("principal").updateOne({ id }, { $set: { roles } });
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setPrincipalAttributesById(id: string, attr: Record<string, any>): Promise<void> {
|
|
||||||
await db.collection("principal").updateOne({ id }, { $set: { attr } });
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieve a principal for a better-auth user.
|
|
||||||
*
|
|
||||||
* @param userId - User id from better-auth user list.
|
|
||||||
*/
|
|
||||||
export async function getPrincipalByUserId(userId: string): Promise<Principal> {
|
|
||||||
const principal = await db.collection("principal").findOneAndUpdate(
|
|
||||||
{ id: userId },
|
|
||||||
{
|
|
||||||
$setOnInsert: {
|
|
||||||
id: userId,
|
|
||||||
type: {
|
|
||||||
id: PrincipalTypeId.User,
|
|
||||||
name: PRINCIPAL_TYPE_NAMES[PrincipalTypeId.User],
|
|
||||||
},
|
|
||||||
roles: ["user"],
|
|
||||||
attr: {},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{ upsert: true, returnDocument: "after" },
|
|
||||||
);
|
|
||||||
if (principal === null) {
|
|
||||||
throw new Error("Failed to resolve Principal");
|
|
||||||
}
|
|
||||||
return PrincipalSchema.parse(principal);
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
import { logger as platformLogger } from "@platform/logger";
|
|
||||||
|
|
||||||
export const logger = platformLogger.prefix("Modules/Identity");
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
import cookie from "cookie";
|
|
||||||
|
|
||||||
import { config } from "../config.ts";
|
|
||||||
import { auth } from "./auth.ts";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get session headers which can be applied on a Response object to apply
|
|
||||||
* an authenticated session to the respondent.
|
|
||||||
*
|
|
||||||
* @param accessToken - Token to apply to the cookie.
|
|
||||||
* @param maxAge - Max age of the token.
|
|
||||||
*/
|
|
||||||
export async function getSessionHeaders(accessToken: string, maxAge: number): Promise<Headers> {
|
|
||||||
return new Headers({
|
|
||||||
"set-cookie": cookie.serialize(
|
|
||||||
"better-auth.session_token",
|
|
||||||
encodeURIComponent(accessToken), // URL-encode the token
|
|
||||||
config.cookie(maxAge),
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get session container from request headers.
|
|
||||||
*
|
|
||||||
* @param headers - Request headers to extract session from.
|
|
||||||
*/
|
|
||||||
export async function getSessionByRequestHeader(headers: Headers) {
|
|
||||||
const response = await auth.api.getSession({ headers });
|
|
||||||
if (response === null) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return response.session;
|
|
||||||
}
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
import "@platform/relay";
|
|
||||||
import "@platform/storage";
|
|
||||||
|
|
||||||
import type { Session } from "better-auth";
|
|
||||||
|
|
||||||
import type { identity } from "./client.ts";
|
|
||||||
import type { Principal } from "./models/principal.ts";
|
|
||||||
|
|
||||||
declare module "@platform/storage" {
|
|
||||||
interface StorageContext {
|
|
||||||
/**
|
|
||||||
* TODO ...
|
|
||||||
*/
|
|
||||||
session?: Session;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TODO ...
|
|
||||||
*/
|
|
||||||
principal?: Principal;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TODO ...
|
|
||||||
*/
|
|
||||||
access?: typeof identity.access;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
declare module "@platform/relay" {
|
|
||||||
interface ServerContext {
|
|
||||||
/**
|
|
||||||
* TODO ...
|
|
||||||
*/
|
|
||||||
isAuthenticated: boolean;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TODO ...
|
|
||||||
*/
|
|
||||||
session: Session;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TODO ...
|
|
||||||
*/
|
|
||||||
principal: Principal;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TODO ...
|
|
||||||
*/
|
|
||||||
access: typeof identity.access;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user