mirror of
https://github.com/get-drexa/drive.git
synced 2025-11-30 21:41:39 +00:00
refactor: migrate to vite and restructure repo
Co-authored-by: Ona <no-reply@ona.com>
This commit is contained in:
8
packages/convex/_generated/api.d.ts
vendored
8
packages/convex/_generated/api.d.ts
vendored
@@ -20,10 +20,12 @@ import type * as filesystem from "../filesystem.js";
|
||||
import type * as functions from "../functions.js";
|
||||
import type * as http from "../http.js";
|
||||
import type * as model_directories from "../model/directories.js";
|
||||
import type * as model_error from "../model/error.js";
|
||||
import type * as model_files from "../model/files.js";
|
||||
import type * as model_filesystem from "../model/filesystem.js";
|
||||
import type * as model_user from "../model/user.js";
|
||||
import type * as shared_error from "../shared/error.js";
|
||||
import type * as shared_filesystem from "../shared/filesystem.js";
|
||||
import type * as shared_types from "../shared/types.js";
|
||||
import type * as user from "../user.js";
|
||||
|
||||
import type {
|
||||
@@ -53,10 +55,12 @@ declare const fullApi: ApiFromModules<{
|
||||
functions: typeof functions;
|
||||
http: typeof http;
|
||||
"model/directories": typeof model_directories;
|
||||
"model/error": typeof model_error;
|
||||
"model/files": typeof model_files;
|
||||
"model/filesystem": typeof model_filesystem;
|
||||
"model/user": typeof model_user;
|
||||
"shared/error": typeof shared_error;
|
||||
"shared/filesystem": typeof shared_filesystem;
|
||||
"shared/types": typeof shared_types;
|
||||
user: typeof user;
|
||||
}>;
|
||||
declare const fullApiWithMounts: typeof fullApi;
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Id } from "./_generated/dataModel"
|
||||
import { authenticatedMutation, authenticatedQuery, authorizedGet } from "./functions"
|
||||
import * as Directories from "./model/directories"
|
||||
import * as Files from "./model/files"
|
||||
import type { FileSystemItem } from "./model/filesystem"
|
||||
import type { FileSystemItem } from "./shared/filesystem"
|
||||
|
||||
export const generateUploadUrl = authenticatedMutation({
|
||||
handler: async (ctx) => {
|
||||
|
||||
@@ -1,20 +1,27 @@
|
||||
import { v } from "convex/values"
|
||||
import { authenticatedMutation, authenticatedQuery, authorizedGet } from "./functions"
|
||||
import * as Directories from "./model/directories"
|
||||
import * as Err from "./model/error"
|
||||
import * as Files from "./model/files"
|
||||
import type {
|
||||
DirectoryHandle,
|
||||
FileHandle,
|
||||
FileSystemItem,
|
||||
} from "./model/filesystem"
|
||||
import * as FileSystem from "./model/filesystem"
|
||||
import {
|
||||
type FileSystemHandle,
|
||||
FileType,
|
||||
authenticatedMutation,
|
||||
authenticatedQuery,
|
||||
authorizedGet,
|
||||
} from "./functions"
|
||||
import * as Directories from "./model/directories"
|
||||
import * as Files from "./model/files"
|
||||
import {
|
||||
deleteItemsPermanently,
|
||||
emptyTrash as emptyTrashImpl,
|
||||
fetchFileUrl as fetchFileUrlImpl,
|
||||
restoreItems as restoreItemsImpl,
|
||||
VDirectoryHandle,
|
||||
VFileSystemHandle,
|
||||
} from "./model/filesystem"
|
||||
import * as Err from "./shared/error"
|
||||
import type {
|
||||
DirectoryHandle,
|
||||
FileHandle,
|
||||
FileSystemHandle,
|
||||
FileSystemItem,
|
||||
} from "./shared/filesystem"
|
||||
import { FileType } from "./shared/filesystem"
|
||||
|
||||
export const moveItems = authenticatedMutation({
|
||||
args: {
|
||||
@@ -22,7 +29,10 @@ export const moveItems = authenticatedMutation({
|
||||
items: v.array(VFileSystemHandle),
|
||||
},
|
||||
handler: async (ctx, { targetDirectory: targetDirectoryHandle, items }) => {
|
||||
const targetDirectory = await authorizedGet(ctx, targetDirectoryHandle.id)
|
||||
const targetDirectory = await authorizedGet(
|
||||
ctx,
|
||||
targetDirectoryHandle.id,
|
||||
)
|
||||
if (!targetDirectory) {
|
||||
throw Err.create(
|
||||
Err.Code.DirectoryNotFound,
|
||||
@@ -131,13 +141,13 @@ export const permanentlyDeleteItems = authenticatedMutation({
|
||||
handles: v.array(VFileSystemHandle),
|
||||
},
|
||||
handler: async (ctx, { handles }) => {
|
||||
return await FileSystem.deleteItemsPermanently(ctx, { handles })
|
||||
return await deleteItemsPermanently(ctx, { handles })
|
||||
},
|
||||
})
|
||||
|
||||
export const emptyTrash = authenticatedMutation({
|
||||
handler: async (ctx) => {
|
||||
return await FileSystem.emptyTrash(ctx)
|
||||
return await emptyTrashImpl(ctx)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -146,7 +156,7 @@ export const restoreItems = authenticatedMutation({
|
||||
handles: v.array(VFileSystemHandle),
|
||||
},
|
||||
handler: async (ctx, { handles }) => {
|
||||
return await FileSystem.restoreItems(ctx, { handles })
|
||||
return await restoreItemsImpl(ctx, { handles })
|
||||
},
|
||||
})
|
||||
|
||||
@@ -155,11 +165,6 @@ export const fetchFileUrl = authenticatedQuery({
|
||||
fileId: v.id("files"),
|
||||
},
|
||||
handler: async (ctx, { fileId }) => {
|
||||
const file = await authorizedGet(ctx, fileId)
|
||||
if (!file) {
|
||||
throw Err.create(Err.Code.NotFound, "File not found")
|
||||
}
|
||||
|
||||
return await FileSystem.fetchFileUrl(ctx, { fileId })
|
||||
return await fetchFileUrlImpl(ctx, { fileId })
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import type { Doc, Id } from "@fileone/convex/_generated/dataModel"
|
||||
import type { Doc, Id } from "../_generated/dataModel"
|
||||
import type {
|
||||
AuthenticatedMutationCtx,
|
||||
AuthenticatedQueryCtx,
|
||||
} from "../functions"
|
||||
import { authorizedGet } from "../functions"
|
||||
import * as Err from "./error"
|
||||
import * as Err from "../shared/error"
|
||||
import {
|
||||
type DirectoryHandle,
|
||||
type DirectoryPath,
|
||||
type FileSystemItem,
|
||||
FileType,
|
||||
newDirectoryHandle,
|
||||
} from "./filesystem"
|
||||
} from "../shared/filesystem"
|
||||
|
||||
export type DirectoryInfo = Doc<"directories"> & { path: DirectoryPath }
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Doc, Id } from "../_generated/dataModel"
|
||||
import { type AuthenticatedMutationCtx, authorizedGet } from "../functions"
|
||||
import * as Err from "./error"
|
||||
import type { DirectoryHandle, FileHandle } from "./filesystem"
|
||||
import * as Err from "../shared/error"
|
||||
import type { DirectoryHandle, FileHandle } from "../shared/filesystem"
|
||||
|
||||
export async function renameFile(
|
||||
ctx: AuthenticatedMutationCtx,
|
||||
|
||||
@@ -1,89 +1,24 @@
|
||||
import { v } from "convex/values"
|
||||
import type { Doc, Id } from "../_generated/dataModel"
|
||||
import type {
|
||||
AuthenticatedMutationCtx,
|
||||
AuthenticatedQueryCtx,
|
||||
import {
|
||||
type AuthenticatedMutationCtx,
|
||||
type AuthenticatedQueryCtx,
|
||||
authorizedGet,
|
||||
} from "../functions"
|
||||
import { authorizedGet } from "../functions"
|
||||
import * as Err from "../shared/error"
|
||||
import type {
|
||||
DirectoryHandle,
|
||||
FileHandle,
|
||||
FileSystemHandle,
|
||||
} from "../shared/filesystem"
|
||||
import {
|
||||
FileType,
|
||||
newDirectoryHandle,
|
||||
newFileHandle,
|
||||
} from "../shared/filesystem"
|
||||
import * as Directories from "./directories"
|
||||
import * as Err from "./error"
|
||||
import * as Files from "./files"
|
||||
|
||||
export enum FileType {
|
||||
File = "File",
|
||||
Directory = "Directory",
|
||||
}
|
||||
|
||||
export type Directory = {
|
||||
kind: FileType.Directory
|
||||
doc: Doc<"directories">
|
||||
}
|
||||
export type File = {
|
||||
kind: FileType.File
|
||||
doc: Doc<"files">
|
||||
}
|
||||
export type FileSystemItem = Directory | File
|
||||
|
||||
export type DirectoryPathComponent = {
|
||||
handle: DirectoryHandle
|
||||
name: string
|
||||
}
|
||||
|
||||
export type FilePathComponent = {
|
||||
handle: FileHandle
|
||||
name: string
|
||||
}
|
||||
export type PathComponent = FilePathComponent | DirectoryPathComponent
|
||||
export type DirectoryPath = [
|
||||
DirectoryPathComponent,
|
||||
...DirectoryPathComponent[],
|
||||
]
|
||||
export type FilePath = [...DirectoryPathComponent[], PathComponent]
|
||||
export type ReverseFilePath = [PathComponent, ...DirectoryPathComponent[]]
|
||||
|
||||
export type DirectoryHandle = {
|
||||
kind: FileType.Directory
|
||||
id: Id<"directories">
|
||||
}
|
||||
export type FileHandle = {
|
||||
kind: FileType.File
|
||||
id: Id<"files">
|
||||
}
|
||||
export type FileSystemHandle = DirectoryHandle | FileHandle
|
||||
|
||||
export type DeleteResult = {
|
||||
deleted: {
|
||||
files: number
|
||||
directories: number
|
||||
}
|
||||
errors: Err.ApplicationErrorData[]
|
||||
}
|
||||
|
||||
export function newFileSystemHandle(item: FileSystemItem): FileSystemHandle {
|
||||
console.log("item", item)
|
||||
switch (item.kind) {
|
||||
case FileType.File:
|
||||
return { kind: item.kind, id: item.doc._id }
|
||||
case FileType.Directory:
|
||||
return { kind: item.kind, id: item.doc._id }
|
||||
}
|
||||
}
|
||||
|
||||
export function isSameHandle(
|
||||
handle1: FileSystemHandle,
|
||||
handle2: FileSystemHandle,
|
||||
): boolean {
|
||||
return handle1.kind === handle2.kind && handle1.id === handle2.id
|
||||
}
|
||||
|
||||
export function newDirectoryHandle(id: Id<"directories">): DirectoryHandle {
|
||||
return { kind: FileType.Directory, id }
|
||||
}
|
||||
|
||||
export function newFileHandle(id: Id<"files">): FileHandle {
|
||||
return { kind: FileType.File, id }
|
||||
}
|
||||
|
||||
export const VDirectoryHandle = v.object({
|
||||
kind: v.literal(FileType.Directory),
|
||||
id: v.id("directories"),
|
||||
@@ -95,7 +30,7 @@ export const VFileHandle = v.object({
|
||||
export const VFileSystemHandle = v.union(VFileHandle, VDirectoryHandle)
|
||||
|
||||
export async function queryRootDirectory(
|
||||
ctx: AuthenticatedQueryCtx,
|
||||
ctx: AuthenticatedQueryCtx | AuthenticatedMutationCtx,
|
||||
): Promise<Doc<"directories"> | null> {
|
||||
return await ctx.db
|
||||
.query("directories")
|
||||
@@ -134,24 +69,19 @@ async function collectAllHandlesRecursively(
|
||||
const fileHandles: FileHandle[] = []
|
||||
const directoryHandles: DirectoryHandle[] = []
|
||||
|
||||
// Process each handle to collect files and directories
|
||||
for (const handle of handles) {
|
||||
// Use a queue to process items iteratively instead of recursively
|
||||
const queue: FileSystemHandle[] = [handle]
|
||||
|
||||
while (queue.length > 0) {
|
||||
const currentHandle = queue.shift()!
|
||||
|
||||
// Add current item to appropriate collection
|
||||
if (currentHandle.kind === FileType.File) {
|
||||
fileHandles.push(currentHandle)
|
||||
} else {
|
||||
directoryHandles.push(currentHandle)
|
||||
}
|
||||
|
||||
// If it's a directory, collect all children and add them to the queue
|
||||
if (currentHandle.kind === FileType.Directory) {
|
||||
// Get all child directories that are in trash (deletedAt >= 0)
|
||||
const childDirectories = await ctx.db
|
||||
.query("directories")
|
||||
.withIndex("byParentId", (q) =>
|
||||
@@ -162,7 +92,6 @@ async function collectAllHandlesRecursively(
|
||||
)
|
||||
.collect()
|
||||
|
||||
// Get all child files that are in trash (deletedAt >= 0)
|
||||
const childFiles = await ctx.db
|
||||
.query("files")
|
||||
.withIndex("byDirectoryId", (q) =>
|
||||
@@ -173,16 +102,12 @@ async function collectAllHandlesRecursively(
|
||||
)
|
||||
.collect()
|
||||
|
||||
// Add child directories to queue for processing
|
||||
for (const childDir of childDirectories) {
|
||||
const childHandle = newDirectoryHandle(childDir._id)
|
||||
queue.push(childHandle)
|
||||
queue.push(newDirectoryHandle(childDir._id))
|
||||
}
|
||||
|
||||
// Add child files to file handles collection
|
||||
for (const childFile of childFiles) {
|
||||
const childFileHandle = newFileHandle(childFile._id)
|
||||
fileHandles.push(childFileHandle)
|
||||
fileHandles.push(newFileHandle(childFile._id))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -199,17 +124,14 @@ export async function restoreItems(
|
||||
ctx: AuthenticatedMutationCtx,
|
||||
{ handles }: { handles: FileSystemHandle[] },
|
||||
) {
|
||||
// Collect all items to restore (including nested items)
|
||||
const { fileHandles, directoryHandles } =
|
||||
await collectAllHandlesRecursively(ctx, { handles })
|
||||
|
||||
// Restore files and directories by unsetting deletedAt
|
||||
const [filesResult, directoriesResult] = await Promise.all([
|
||||
Files.restore(ctx, { items: fileHandles }),
|
||||
Directories.restore(ctx, { items: directoryHandles }),
|
||||
])
|
||||
|
||||
// Combine results, handling null responses
|
||||
return {
|
||||
restored: {
|
||||
files: filesResult?.restored || 0,
|
||||
@@ -225,20 +147,15 @@ export async function restoreItems(
|
||||
export async function deleteItemsPermanently(
|
||||
ctx: AuthenticatedMutationCtx,
|
||||
{ handles }: { handles: FileSystemHandle[] },
|
||||
): Promise<DeleteResult> {
|
||||
// Collect all items to delete (including nested items)
|
||||
const {
|
||||
fileHandles: fileHandlesToDelete,
|
||||
directoryHandles: directoryHandlesToDelete,
|
||||
} = await collectAllHandlesRecursively(ctx, { handles })
|
||||
) {
|
||||
const { fileHandles, directoryHandles } =
|
||||
await collectAllHandlesRecursively(ctx, { handles })
|
||||
|
||||
// Delete files and directories using their respective models
|
||||
const [filesResult, directoriesResult] = await Promise.all([
|
||||
Files.deletePermanently(ctx, { items: fileHandlesToDelete }),
|
||||
Directories.deletePermanently(ctx, { items: directoryHandlesToDelete }),
|
||||
Files.deletePermanently(ctx, { items: fileHandles }),
|
||||
Directories.deletePermanently(ctx, { items: directoryHandles }),
|
||||
])
|
||||
|
||||
// Combine results, handling null responses
|
||||
return {
|
||||
deleted: {
|
||||
files: filesResult?.deleted || 0,
|
||||
@@ -251,9 +168,7 @@ export async function deleteItemsPermanently(
|
||||
}
|
||||
}
|
||||
|
||||
export async function emptyTrash(
|
||||
ctx: AuthenticatedMutationCtx,
|
||||
): Promise<DeleteResult> {
|
||||
export async function emptyTrash(ctx: AuthenticatedMutationCtx) {
|
||||
const rootDir = await queryRootDirectory(ctx)
|
||||
if (!rootDir) {
|
||||
throw Err.create(Err.Code.NotFound, "user root directory not found")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { MutationCtx, QueryCtx } from "../_generated/server"
|
||||
import { authComponent } from "../auth"
|
||||
import * as Err from "./error"
|
||||
import * as Err from "../shared/error"
|
||||
|
||||
export type AuthUser = Awaited<ReturnType<typeof authComponent.getAuthUser>>
|
||||
|
||||
|
||||
@@ -2,6 +2,14 @@
|
||||
"name": "@fileone/convex",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./filesystem": "./shared/filesystem.ts",
|
||||
"./error": "./shared/error.ts",
|
||||
"./types": "./shared/types.ts",
|
||||
"./_generated/*": "./_generated/*",
|
||||
"./model/*": "./model/*",
|
||||
"./shared/*": "./shared/*"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fileone/path": "workspace:*"
|
||||
},
|
||||
@@ -9,6 +17,7 @@
|
||||
"typescript": "^5",
|
||||
"better-auth": "1.3.8",
|
||||
"convex": "^1.27.0",
|
||||
"convex-helpers": "^0.1.104",
|
||||
"@convex-dev/better-auth": "^0.8.9"
|
||||
}
|
||||
}
|
||||
|
||||
91
packages/convex/shared/filesystem.ts
Normal file
91
packages/convex/shared/filesystem.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Client-safe filesystem types and utilities.
|
||||
* This file contains types and pure functions that can be safely imported by frontend code.
|
||||
* NO server-only dependencies should be imported here.
|
||||
*/
|
||||
|
||||
import type { Doc, Id } from "../_generated/dataModel"
|
||||
import type * as Err from "./error"
|
||||
|
||||
export enum FileType {
|
||||
File = "File",
|
||||
Directory = "Directory",
|
||||
}
|
||||
|
||||
export type Directory = {
|
||||
kind: FileType.Directory
|
||||
doc: Doc<"directories">
|
||||
}
|
||||
|
||||
export type File = {
|
||||
kind: FileType.File
|
||||
doc: Doc<"files">
|
||||
}
|
||||
|
||||
export type FileSystemItem = Directory | File
|
||||
|
||||
export type DirectoryPathComponent = {
|
||||
handle: DirectoryHandle
|
||||
name: string
|
||||
}
|
||||
|
||||
export type FilePathComponent = {
|
||||
handle: FileHandle
|
||||
name: string
|
||||
}
|
||||
|
||||
export type PathComponent = FilePathComponent | DirectoryPathComponent
|
||||
|
||||
export type DirectoryPath = [
|
||||
DirectoryPathComponent,
|
||||
...DirectoryPathComponent[],
|
||||
]
|
||||
|
||||
export type FilePath = [...DirectoryPathComponent[], PathComponent]
|
||||
|
||||
export type ReverseFilePath = [PathComponent, ...DirectoryPathComponent[]]
|
||||
|
||||
export type DirectoryHandle = {
|
||||
kind: FileType.Directory
|
||||
id: Id<"directories">
|
||||
}
|
||||
|
||||
export type FileHandle = {
|
||||
kind: FileType.File
|
||||
id: Id<"files">
|
||||
}
|
||||
|
||||
export type FileSystemHandle = DirectoryHandle | FileHandle
|
||||
|
||||
export type DeleteResult = {
|
||||
deleted: {
|
||||
files: number
|
||||
directories: number
|
||||
}
|
||||
errors: Err.ApplicationErrorData[]
|
||||
}
|
||||
|
||||
export function newFileSystemHandle(item: FileSystemItem): FileSystemHandle {
|
||||
console.log("item", item)
|
||||
switch (item.kind) {
|
||||
case FileType.File:
|
||||
return { kind: item.kind, id: item.doc._id }
|
||||
case FileType.Directory:
|
||||
return { kind: item.kind, id: item.doc._id }
|
||||
}
|
||||
}
|
||||
|
||||
export function isSameHandle(
|
||||
handle1: FileSystemHandle,
|
||||
handle2: FileSystemHandle,
|
||||
): boolean {
|
||||
return handle1.kind === handle2.kind && handle1.id === handle2.id
|
||||
}
|
||||
|
||||
export function newDirectoryHandle(id: Id<"directories">): DirectoryHandle {
|
||||
return { kind: FileType.Directory, id }
|
||||
}
|
||||
|
||||
export function newFileHandle(id: Id<"files">): FileHandle {
|
||||
return { kind: FileType.File, id }
|
||||
}
|
||||
11
packages/convex/shared/types.ts
Normal file
11
packages/convex/shared/types.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Shared types that can be safely imported by both client and server code.
|
||||
* This file should NOT import any server-only dependencies.
|
||||
*/
|
||||
|
||||
import type { Doc } from "../_generated/dataModel"
|
||||
import type { DirectoryPath } from "./filesystem"
|
||||
|
||||
export type DirectoryInfo = Doc<"directories"> & { path: DirectoryPath }
|
||||
export type DirectoryItem = DirectoryInfo
|
||||
export type DirectoryItemKind = "directory" | "file"
|
||||
@@ -1,8 +1,8 @@
|
||||
import { authenticatedMutation } from "./functions"
|
||||
import * as FileSystem from "./model/filesystem"
|
||||
import { ensureRootDirectory as ensureRootDirectoryImpl } from "./model/filesystem"
|
||||
|
||||
export const ensureRootDirectory = authenticatedMutation({
|
||||
handler: async (ctx) => {
|
||||
return await FileSystem.ensureRootDirectory(ctx)
|
||||
return await ensureRootDirectoryImpl(ctx)
|
||||
},
|
||||
})
|
||||
|
||||
17
packages/web/bun-env.d.ts
vendored
17
packages/web/bun-env.d.ts
vendored
@@ -1,17 +0,0 @@
|
||||
// Generated by `bun init`
|
||||
|
||||
declare module "*.svg" {
|
||||
/**
|
||||
* A path to the SVG file
|
||||
*/
|
||||
const path: `${string}.svg`
|
||||
export = path
|
||||
}
|
||||
|
||||
declare module "*.module.css" {
|
||||
/**
|
||||
* A record of class names to their corresponding CSS module classes
|
||||
*/
|
||||
const classes: { readonly [key: string]: string }
|
||||
export = classes
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
[serve.static]
|
||||
env = "BUN_PUBLIC_*"
|
||||
plugins = ["bun-plugin-tailwind"]
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/styles/globals.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
{
|
||||
"name": "@fileone/web",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "bun --hot src/server.tsx",
|
||||
"build": "bun build ./src/index.html --outdir=dist --sourcemap --target=browser --minify --define:process.env.NODE_ENV='\"production\"' --env='BUN_PUBLIC_*'",
|
||||
"start": "NODE_ENV=production bun src/index.tsx",
|
||||
"format": "biome format --write"
|
||||
},
|
||||
"dependencies": {
|
||||
"@convex-dev/better-auth": "^0.8.9",
|
||||
"@fileone/convex": "workspace:*",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-context-menu": "^2.2.16",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
"@radix-ui/react-label": "^2.1.7",
|
||||
"@radix-ui/react-progress": "^1.1.7",
|
||||
"@radix-ui/react-separator": "^1.1.7",
|
||||
"@radix-ui/react-slot": "^1.2.3",
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@tanstack/react-query": "^5.87.4",
|
||||
"@tanstack/react-router": "^1.131.41",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@tanstack/router-devtools": "^1.131.42",
|
||||
"better-auth": "1.3.8",
|
||||
"bun-plugin-tailwind": "latest",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"convex": "^1.27.0",
|
||||
"convex-helpers": "^0.1.104",
|
||||
"jotai": "^2.14.0",
|
||||
"jotai-effect": "^2.1.3",
|
||||
"jotai-scope": "^0.9.5",
|
||||
"jotai-tanstack-query": "^0.11.0",
|
||||
"lucide-react": "^0.544.0",
|
||||
"motion": "^12.23.16",
|
||||
"nanoid": "^5.1.6",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "^19",
|
||||
"react-dom": "^19",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"tailwindcss": "^4",
|
||||
"tw-animate-css": "^1.3.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tanstack/router-cli": "^1.131.41",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19"
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import { useRef, type FormEvent } from "react";
|
||||
|
||||
export function APITester() {
|
||||
const responseInputRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
const testEndpoint = async (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
|
||||
try {
|
||||
const form = e.currentTarget;
|
||||
const formData = new FormData(form);
|
||||
const endpoint = formData.get("endpoint") as string;
|
||||
const url = new URL(endpoint, location.href);
|
||||
const method = formData.get("method") as string;
|
||||
const res = await fetch(url, { method });
|
||||
|
||||
const data = await res.json();
|
||||
responseInputRef.current!.value = JSON.stringify(data, null, 2);
|
||||
} catch (error) {
|
||||
responseInputRef.current!.value = String(error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="api-tester">
|
||||
<form onSubmit={testEndpoint} className="endpoint-row">
|
||||
<select name="method" className="method">
|
||||
<option value="GET">GET</option>
|
||||
<option value="PUT">PUT</option>
|
||||
</select>
|
||||
<input type="text" name="endpoint" defaultValue="/api/hello" className="url-input" placeholder="/api/hello" />
|
||||
<button type="submit" className="send-button">
|
||||
Send
|
||||
</button>
|
||||
</form>
|
||||
<textarea ref={responseInputRef} readOnly placeholder="Response will appear here..." className="response-area" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import {
|
||||
convexClient,
|
||||
crossDomainClient,
|
||||
} from "@convex-dev/better-auth/client/plugins"
|
||||
import { createAuthClient } from "better-auth/react"
|
||||
import { createContext, useContext } from "react"
|
||||
|
||||
export type AuthErrorCode = keyof typeof authClient.$ERROR_CODES
|
||||
|
||||
export class BetterAuthError extends Error {
|
||||
constructor(public readonly errorCode: AuthErrorCode) {
|
||||
super(`better-auth error: ${errorCode}`)
|
||||
}
|
||||
}
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: process.env.BUN_PUBLIC_CONVEX_SITE_URL,
|
||||
plugins: [convexClient(), crossDomainClient()],
|
||||
})
|
||||
|
||||
export type Session = NonNullable<
|
||||
Awaited<ReturnType<typeof authClient.useSession>>["data"]
|
||||
>
|
||||
|
||||
export const SessionContext = createContext<Session | null>(null)
|
||||
|
||||
export function useSession() {
|
||||
const context = useContext(SessionContext)
|
||||
if (!context) {
|
||||
throw new Error("useSession must be used within a SessionProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
export function DirectoryIcon({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
className={cn(
|
||||
"icon icon-tabler icons-tabler-filled icon-tabler-folder text-orange-300",
|
||||
className,
|
||||
)}
|
||||
aria-label="Directory"
|
||||
>
|
||||
<title>Directory</title>
|
||||
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||
<path d="M9 3a1 1 0 0 1 .608 .206l.1 .087l2.706 2.707h6.586a3 3 0 0 1 2.995 2.824l.005 .176v8a3 3 0 0 1 -2.824 2.995l-.176 .005h-14a3 3 0 0 1 -2.995 -2.824l-.005 -.176v-11a3 3 0 0 1 2.824 -2.995l.176 -.005h4z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import type React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
export function TextFileIcon({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"svg">) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
className={cn(
|
||||
"icon icon-tabler icons-tabler-filled icon-tabler-file-text text-blue-300",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<title>Text File</title>
|
||||
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||
<path d="M12 2l.117 .007a1 1 0 0 1 .876 .876l.007 .117v4l.005 .15a2 2 0 0 0 1.838 1.844l.157 .006h4l.117 .007a1 1 0 0 1 .876 .876l.007 .117v9a3 3 0 0 1 -2.824 2.995l-.176 .005h-10a3 3 0 0 1 -2.995 -2.824l-.005 -.176v-14a3 3 0 0 1 2.824 -2.995l.176 -.005zm3 14h-6a1 1 0 0 0 0 2h6a1 1 0 0 0 0 -2m0 -4h-6a1 1 0 0 0 0 2h6a1 1 0 0 0 0 -2m-5 -4h-1a1 1 0 1 0 0 2h1a1 1 0 0 0 0 -2" />
|
||||
<path d="M19 7h-4l-.001 -4.001z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
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 function useTheme() {
|
||||
const context = useContext(ThemeProviderContext)
|
||||
|
||||
if (!context)
|
||||
throw new Error("useTheme must be used within a ThemeProvider")
|
||||
|
||||
return context
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { ChevronRight, MoreHorizontal } from "lucide-react"
|
||||
import type * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
|
||||
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />
|
||||
}
|
||||
|
||||
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
|
||||
return (
|
||||
<ol
|
||||
data-slot="breadcrumb-list"
|
||||
className={cn(
|
||||
"text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="breadcrumb-item"
|
||||
className={cn("inline-flex items-center gap-1.5", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbLink({
|
||||
asChild,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="breadcrumb-link"
|
||||
className={cn("hover:text-foreground transition-colors", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="breadcrumb-page"
|
||||
role="link"
|
||||
aria-disabled="true"
|
||||
aria-current="page"
|
||||
className={cn("text-foreground font-normal", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbSeparator({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="breadcrumb-separator"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("[&>svg]:size-3.5", className)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? <ChevronRight />}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbEllipsis({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="breadcrumb-ellipsis"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("flex size-9 items-center justify-center", className)}
|
||||
{...props}
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
<span className="sr-only">More</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Breadcrumb,
|
||||
BreadcrumbList,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbLink,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
BreadcrumbEllipsis,
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import type * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { LoadingSpinner } from "./loading-spinner"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none 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",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
loading = false,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
loading?: boolean
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
disabled={props.disabled}
|
||||
{...props}
|
||||
>
|
||||
{asChild ? (
|
||||
children
|
||||
) : (
|
||||
<>
|
||||
{loading ? <LoadingSpinner /> : null}
|
||||
{children}
|
||||
</>
|
||||
)}
|
||||
</Comp>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -1,92 +0,0 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
import type * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="flex items-center justify-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
@@ -1,256 +0,0 @@
|
||||
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
import type * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ContextMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Trigger
|
||||
data-slot="context-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal
|
||||
data-slot="context-menu-portal"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioGroup
|
||||
data-slot="context-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubTrigger
|
||||
data-slot="context-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto" />
|
||||
</ContextMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubContent
|
||||
data-slot="context-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.Content
|
||||
data-slot="context-menu-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Item
|
||||
data-slot="context-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.CheckboxItem
|
||||
data-slot="context-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioItem
|
||||
data-slot="context-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Label
|
||||
data-slot="context-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Separator
|
||||
data-slot="context-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="context-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
ContextMenu,
|
||||
ContextMenuTrigger,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuCheckboxItem,
|
||||
ContextMenuRadioItem,
|
||||
ContextMenuLabel,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuShortcut,
|
||||
ContextMenuGroup,
|
||||
ContextMenuPortal,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuRadioGroup,
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
import {
|
||||
type ColumnDef,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
type Row,
|
||||
useReactTable,
|
||||
} from "@tanstack/react-table"
|
||||
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
|
||||
interface DataTableProps<TData, TValue> {
|
||||
columns: ColumnDef<TData, TValue>[]
|
||||
data: TData[]
|
||||
onRowContextMenu?: (row: Row<TData>, event: React.MouseEvent) => void
|
||||
}
|
||||
|
||||
export function DataTable<TData, TValue>({
|
||||
columns,
|
||||
data,
|
||||
onRowContextMenu,
|
||||
}: DataTableProps<TData, TValue>) {
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
enableRowSelection: true,
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="overflow-hidden rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id}>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef
|
||||
.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && "selected"}
|
||||
onContextMenu={(e) => {
|
||||
onRowContextMenu?.(row, e)
|
||||
}}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>
|
||||
{flexRender(
|
||||
cell.column.columnDef.cell,
|
||||
cell.getContext(),
|
||||
)}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell
|
||||
colSpan={columns.length}
|
||||
className="h-24 text-center"
|
||||
>
|
||||
No results.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
import type * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-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/20",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground 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 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||
>
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn(
|
||||
"flex flex-col gap-2 text-center sm:text-left",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
@@ -1,263 +0,0 @@
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
import type * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal
|
||||
data-slot="dropdown-menu-portal"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 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 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group
|
||||
data-slot="dropdown-menu-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
}
|
||||
@@ -1,242 +0,0 @@
|
||||
import { useMemo } from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
|
||||
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
|
||||
return (
|
||||
<fieldset
|
||||
data-slot="field-set"
|
||||
className={cn(
|
||||
"flex flex-col gap-6",
|
||||
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldLegend({
|
||||
className,
|
||||
variant = "legend",
|
||||
...props
|
||||
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
|
||||
return (
|
||||
<legend
|
||||
data-slot="field-legend"
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"mb-3 font-medium",
|
||||
"data-[variant=legend]:text-base",
|
||||
"data-[variant=label]:text-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="field-group"
|
||||
className={cn(
|
||||
"group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const fieldVariants = cva(
|
||||
"group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
|
||||
{
|
||||
variants: {
|
||||
orientation: {
|
||||
vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"],
|
||||
horizontal: [
|
||||
"flex-row items-center",
|
||||
"[&>[data-slot=field-label]]:flex-auto",
|
||||
"has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
||||
],
|
||||
responsive: [
|
||||
"flex-col [&>*]:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto",
|
||||
"@md/field-group:[&>[data-slot=field-label]]:flex-auto",
|
||||
"@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
||||
],
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
orientation: "vertical",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Field({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
data-slot="field"
|
||||
data-orientation={orientation}
|
||||
className={cn(fieldVariants({ orientation }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="field-content"
|
||||
className={cn(
|
||||
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Label>) {
|
||||
return (
|
||||
<Label
|
||||
data-slot="field-label"
|
||||
className={cn(
|
||||
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
|
||||
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4",
|
||||
"has-data-[state=checked]:bg-primary/5 has-data-[state=checked]:border-primary dark:has-data-[state=checked]:bg-primary/10",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="field-label"
|
||||
className={cn(
|
||||
"flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
return (
|
||||
<p
|
||||
data-slot="field-description"
|
||||
className={cn(
|
||||
"text-muted-foreground text-sm leading-normal font-normal group-has-[[data-orientation=horizontal]]/field:text-balance",
|
||||
"last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
|
||||
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldSeparator({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
children?: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="field-separator"
|
||||
data-content={!!children}
|
||||
className={cn(
|
||||
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<Separator className="absolute inset-0 top-1/2" />
|
||||
{children && (
|
||||
<span
|
||||
className="bg-background text-muted-foreground relative mx-auto block w-fit px-2"
|
||||
data-slot="field-separator-content"
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldError({
|
||||
className,
|
||||
children,
|
||||
errors,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
errors?: Array<{ message?: string } | undefined>
|
||||
}) {
|
||||
const content = useMemo(() => {
|
||||
if (children) {
|
||||
return children
|
||||
}
|
||||
|
||||
if (!errors) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (errors?.length === 1 && errors[0]?.message) {
|
||||
return errors[0].message
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="ml-4 flex list-disc flex-col gap-1">
|
||||
{errors.map(
|
||||
(error, index) =>
|
||||
error?.message && <li key={index}>{error.message}</li>
|
||||
)}
|
||||
</ul>
|
||||
)
|
||||
}, [children, errors])
|
||||
|
||||
if (!content) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
data-slot="field-error"
|
||||
className={cn("text-destructive text-sm font-normal", className)}
|
||||
{...props}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Field,
|
||||
FieldLabel,
|
||||
FieldDescription,
|
||||
FieldError,
|
||||
FieldGroup,
|
||||
FieldLegend,
|
||||
FieldSeparator,
|
||||
FieldSet,
|
||||
FieldContent,
|
||||
FieldTitle,
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import type * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/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 flex 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 }
|
||||
@@ -1,22 +0,0 @@
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
@@ -1,6 +0,0 @@
|
||||
import { Loader2Icon } from "lucide-react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
export function LoadingSpinner({ className }: { className?: string }) {
|
||||
return <Loader2Icon className={cn("animate-spin size-4", className)} />
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import * as React from "react"
|
||||
import * as ProgressPrimitive from "@radix-ui/react-progress"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Progress({
|
||||
className,
|
||||
value,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
|
||||
return (
|
||||
<ProgressPrimitive.Root
|
||||
data-slot="progress"
|
||||
className={cn(
|
||||
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ProgressPrimitive.Indicator
|
||||
data-slot="progress-indicator"
|
||||
className="bg-primary h-full w-full flex-1 transition-all"
|
||||
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
|
||||
/>
|
||||
</ProgressPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Progress }
|
||||
@@ -1,28 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
|
||||
import { cn } from "@/lib/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 }
|
||||
@@ -1,139 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
import type * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/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,
|
||||
}
|
||||
@@ -1,741 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { PanelLeftIcon } 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 "@/lib/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
|
||||
}
|
||||
|
||||
function SidebarProvider({
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}) {
|
||||
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])
|
||||
|
||||
// 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, toggleSidebar],
|
||||
)
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<div
|
||||
data-slot="sidebar-wrapper"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function Sidebar({
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right"
|
||||
variant?: "sidebar" | "floating" | "inset"
|
||||
collapsible?: "offcanvas" | "icon" | "none"
|
||||
}) {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar"
|
||||
className={cn(
|
||||
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||
<SheetContent
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar"
|
||||
data-mobile="true"
|
||||
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>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
|
||||
className="group peer text-sidebar-foreground hidden md:block"
|
||||
data-state={state}
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-variant={variant}
|
||||
data-side={side}
|
||||
data-slot="sidebar"
|
||||
>
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
data-slot="sidebar-gap"
|
||||
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)+(--spacing(4)))]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
data-slot="sidebar-container"
|
||||
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)+(--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"
|
||||
data-slot="sidebar-inner"
|
||||
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarTrigger({
|
||||
className,
|
||||
onClick,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-sidebar="trigger"
|
||||
data-slot="sidebar-trigger"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn("size-7", className)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event)
|
||||
toggleSidebar()
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<PanelLeftIcon />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<button
|
||||
data-sidebar="rail"
|
||||
data-slot="sidebar-rail"
|
||||
aria-label="Toggle Sidebar"
|
||||
tabIndex={-1}
|
||||
onClick={toggleSidebar}
|
||||
title="Toggle Sidebar"
|
||||
className={cn(
|
||||
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
|
||||
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||
return (
|
||||
<main
|
||||
data-slot="sidebar-inset"
|
||||
className={cn(
|
||||
"bg-background relative flex w-full flex-1 flex-col",
|
||||
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Input>) {
|
||||
return (
|
||||
<Input
|
||||
data-slot="sidebar-input"
|
||||
data-sidebar="input"
|
||||
className={cn("bg-background h-8 w-full shadow-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-header"
|
||||
data-sidebar="header"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-footer"
|
||||
data-sidebar="footer"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="sidebar-separator"
|
||||
data-sidebar="separator"
|
||||
className={cn("bg-sidebar-border mx-2 w-auto", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-content"
|
||||
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}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group"
|
||||
data-sidebar="group"
|
||||
className={cn(
|
||||
"relative flex w-full min-w-0 flex-col p-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupLabel({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "div"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-label"
|
||||
data-sidebar="group-label"
|
||||
className={cn(
|
||||
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden 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}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupAction({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-action"
|
||||
data-sidebar="group-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group-content"
|
||||
data-sidebar="group-content"
|
||||
className={cn("w-full text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu"
|
||||
data-sidebar="menu"
|
||||
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-item"
|
||||
data-sidebar="menu-item"
|
||||
className={cn("group/menu-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden 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",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
function SidebarMenuButton({
|
||||
asChild = false,
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
isActive?: boolean
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const { isMobile, state } = useSidebar()
|
||||
|
||||
const button = (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-button"
|
||||
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>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuAction({
|
||||
className,
|
||||
asChild = false,
|
||||
showOnHover = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
showOnHover?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-action"
|
||||
data-sidebar="menu-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after: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 &&
|
||||
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuBadge({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-badge"
|
||||
data-sidebar="menu-badge"
|
||||
className={cn(
|
||||
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
|
||||
"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}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSkeleton({
|
||||
className,
|
||||
showIcon = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-skeleton"
|
||||
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>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu-sub"
|
||||
data-sidebar="menu-sub"
|
||||
className={cn(
|
||||
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-sub-item"
|
||||
data-sidebar="menu-sub-item"
|
||||
className={cn("group/menu-sub-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubButton({
|
||||
asChild = false,
|
||||
size = "md",
|
||||
isActive = false,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
size?: "sm" | "md"
|
||||
isActive?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-sub-button"
|
||||
data-sidebar="menu-sub-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 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",
|
||||
"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}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { cn } from "@/lib/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 }
|
||||
@@ -1,24 +0,0 @@
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
position="top-center"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
@@ -1,114 +0,0 @@
|
||||
import type * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="table-container"
|
||||
className="relative w-full overflow-x-auto"
|
||||
>
|
||||
<table
|
||||
data-slot="table"
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
||||
return (
|
||||
<thead
|
||||
data-slot="table-header"
|
||||
className={cn("[&_tr]:border-b", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
||||
return (
|
||||
<tbody
|
||||
data-slot="table-body"
|
||||
className={cn("[&_tr:last-child]:border-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
||||
return (
|
||||
<tfoot
|
||||
data-slot="table-footer"
|
||||
className={cn(
|
||||
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
||||
return (
|
||||
<tr
|
||||
data-slot="table-row"
|
||||
className={cn(
|
||||
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||
return (
|
||||
<th
|
||||
data-slot="table-head"
|
||||
className={cn(
|
||||
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
||||
return (
|
||||
<td
|
||||
data-slot="table-cell"
|
||||
className={cn(
|
||||
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCaption({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"caption">) {
|
||||
return (
|
||||
<caption
|
||||
data-slot="table-caption"
|
||||
className={cn("text-muted-foreground mt-4 text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Table,
|
||||
TableHeader,
|
||||
TableBody,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableCaption,
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
||||
import type * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/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-primary text-primary-foreground 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-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
@@ -1,15 +0,0 @@
|
||||
import { type PrimitiveAtom, useAtom } from "jotai"
|
||||
|
||||
export function WithAtom<Value>({
|
||||
atom,
|
||||
children,
|
||||
}: {
|
||||
atom: PrimitiveAtom<Value>
|
||||
children: (
|
||||
value: Value,
|
||||
setValue: (value: Value | ((current: Value) => Value)) => void,
|
||||
) => React.ReactNode
|
||||
}) {
|
||||
const [value, setValue] = useAtom(atom)
|
||||
return children(value, setValue)
|
||||
}
|
||||
@@ -1,169 +0,0 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import { Link, useLocation } from "@tanstack/react-router"
|
||||
import { useQuery as useConvexQuery } from "convex/react"
|
||||
import { useAtomValue } from "jotai"
|
||||
import {
|
||||
FilesIcon,
|
||||
HomeIcon,
|
||||
LogOutIcon,
|
||||
SettingsIcon,
|
||||
TrashIcon,
|
||||
User2Icon,
|
||||
} from "lucide-react"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarHeader,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
} from "@/components/ui/sidebar"
|
||||
import { LoadingSpinner } from "../components/ui/loading-spinner"
|
||||
import { backgroundTaskProgressAtom } from "./state"
|
||||
|
||||
export function DashboardSidebar() {
|
||||
return (
|
||||
<Sidebar variant="inset" collapsible="icon">
|
||||
<SidebarHeader>
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<UserMenu />
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarHeader>
|
||||
<SidebarContent>
|
||||
<SidebarGroup>
|
||||
<MainSidebarMenu />
|
||||
</SidebarGroup>
|
||||
</SidebarContent>
|
||||
<SidebarFooter>
|
||||
<SidebarMenu>
|
||||
<BackgroundTaskProgressItem />
|
||||
</SidebarMenu>
|
||||
</SidebarFooter>
|
||||
</Sidebar>
|
||||
)
|
||||
}
|
||||
|
||||
function MainSidebarMenu() {
|
||||
const location = useLocation()
|
||||
|
||||
const isActive = (path: string) => {
|
||||
if (path === "/") {
|
||||
return location.pathname === "/"
|
||||
}
|
||||
return location.pathname.startsWith(path)
|
||||
}
|
||||
|
||||
return (
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton asChild isActive={isActive("/")}>
|
||||
<Link to="/">
|
||||
<HomeIcon />
|
||||
<span>Home</span>
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
<AllFilesItem />
|
||||
<TrashItem />
|
||||
</SidebarMenu>
|
||||
)
|
||||
}
|
||||
|
||||
function AllFilesItem() {
|
||||
const location = useLocation()
|
||||
const rootDirectory = useConvexQuery(api.files.fetchRootDirectory)
|
||||
|
||||
if (!rootDirectory) return null
|
||||
|
||||
return (
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
asChild
|
||||
isActive={location.pathname.startsWith("/directories")}
|
||||
>
|
||||
<Link to={`/directories/${rootDirectory._id}`}>
|
||||
<FilesIcon />
|
||||
<span>All Files</span>
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
function TrashItem() {
|
||||
const location = useLocation()
|
||||
const rootDirectory = useConvexQuery(api.files.fetchRootDirectory)
|
||||
|
||||
if (!rootDirectory) return null
|
||||
|
||||
return (
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
asChild
|
||||
isActive={location.pathname.startsWith("/trash/directories")}
|
||||
>
|
||||
<Link to={`/trash/directories/${rootDirectory._id}`}>
|
||||
<TrashIcon />
|
||||
<span>Trash</span>
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
function BackgroundTaskProgressItem() {
|
||||
const backgroundTaskProgress = useAtomValue(backgroundTaskProgressAtom)
|
||||
|
||||
if (!backgroundTaskProgress) return null
|
||||
|
||||
return (
|
||||
<SidebarMenuItem className="flex items-center gap-2 opacity-80 text-sm">
|
||||
<LoadingSpinner />
|
||||
{backgroundTaskProgress.label}
|
||||
</SidebarMenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
function UserMenu() {
|
||||
function handleSignOut() {}
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<SidebarMenuButton size="lg" asChild>
|
||||
<a href="/">
|
||||
<div className="bg-sidebar-primary text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg">
|
||||
<User2Icon className="size-4" />
|
||||
</div>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-medium">
|
||||
Acme Inc
|
||||
</span>
|
||||
<span className="truncate text-xs">Enterprise</span>
|
||||
</div>
|
||||
</a>
|
||||
</SidebarMenuButton>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-64" align="start" side="bottom">
|
||||
<DropdownMenuItem>
|
||||
<SettingsIcon />
|
||||
Settings
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={handleSignOut}>
|
||||
<LogOutIcon />
|
||||
Log out
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
@import url("https://fonts.googleapis.com/css2?family=Geist:wght@100..900&family=Source+Serif+4:ital,opsz,wght@0,8..60,200..900;1,8..60,200..900&display=swap");
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
font-family: Geist, Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
color-scheme: light dark;
|
||||
|
||||
--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);
|
||||
--destructive-foreground: 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);
|
||||
--radius: 0.625rem;
|
||||
--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.145 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.145 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.985 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.396 0.141 25.723);
|
||||
--destructive-foreground: oklch(0.637 0.237 25.331);
|
||||
--border: oklch(0.269 0 0);
|
||||
--input: oklch(0.269 0 0);
|
||||
--ring: oklch(0.439 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(0.269 0 0);
|
||||
--sidebar-ring: oklch(0.439 0 0);
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--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-destructive-foreground: var(--destructive-foreground);
|
||||
--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);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--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);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
div#root {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion) {
|
||||
*,
|
||||
::before,
|
||||
::after {
|
||||
animation: none !important;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { atom } from "jotai"
|
||||
|
||||
type BackgroundTaskProgress = {
|
||||
label: string
|
||||
}
|
||||
|
||||
export const backgroundTaskProgressAtom = atom<BackgroundTaskProgress | null>(
|
||||
null,
|
||||
)
|
||||
@@ -1,14 +0,0 @@
|
||||
import type { Doc } from "@fileone/convex/_generated/dataModel"
|
||||
import type { DirectoryInfo } from "@fileone/convex/model/directories"
|
||||
import type { FileSystemItem } from "@fileone/convex/model/filesystem"
|
||||
import { createContext } from "react"
|
||||
|
||||
type DirectoryPageContextType = {
|
||||
rootDirectory: Doc<"directories">
|
||||
directory: DirectoryInfo
|
||||
directoryContent: FileSystemItem[]
|
||||
}
|
||||
|
||||
export const DirectoryPageContext = createContext<DirectoryPageContextType>(
|
||||
null as unknown as DirectoryPageContextType,
|
||||
)
|
||||
@@ -1,116 +0,0 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import { newFileSystemHandle } from "@fileone/convex/model/filesystem"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { useMutation as useContextMutation } from "convex/react"
|
||||
import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai"
|
||||
import { TextCursorInputIcon, TrashIcon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuTrigger,
|
||||
} from "@/components/ui/context-menu"
|
||||
import {
|
||||
contextMenuTargeItemsAtom,
|
||||
itemBeingRenamedAtom,
|
||||
optimisticDeletedItemsAtom,
|
||||
} from "./state"
|
||||
|
||||
export function DirectoryContentContextMenu({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const store = useStore()
|
||||
const [target, setTarget] = useAtom(contextMenuTargeItemsAtom)
|
||||
const setOptimisticDeletedItems = useSetAtom(optimisticDeletedItemsAtom)
|
||||
const moveToTrashMutation = useContextMutation(api.filesystem.moveToTrash)
|
||||
const { mutate: moveToTrash } = useMutation({
|
||||
mutationFn: moveToTrashMutation,
|
||||
onMutate: ({ handles }) => {
|
||||
setOptimisticDeletedItems(
|
||||
(prev) =>
|
||||
new Set([...prev, ...handles.map((handle) => handle.id)]),
|
||||
)
|
||||
},
|
||||
onSuccess: ({ deleted, errors }, { handles }) => {
|
||||
setOptimisticDeletedItems((prev) => {
|
||||
const newSet = new Set(prev)
|
||||
for (const handle of handles) {
|
||||
newSet.delete(handle.id)
|
||||
}
|
||||
return newSet
|
||||
})
|
||||
if (errors.length === 0 && deleted.length === handles.length) {
|
||||
toast.success(`Moved ${handles.length} items to trash`)
|
||||
} else if (errors.length === handles.length) {
|
||||
toast.error("Failed to move to trash")
|
||||
} else {
|
||||
toast.info(
|
||||
`Moved ${deleted.length} items to trash; failed to move ${errors.length} items`,
|
||||
)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const handleDelete = () => {
|
||||
const selectedItems = store.get(contextMenuTargeItemsAtom)
|
||||
if (selectedItems.length > 0) {
|
||||
moveToTrash({
|
||||
handles: selectedItems.map(newFileSystemHandle),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ContextMenu
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setTarget([])
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
|
||||
{target && (
|
||||
<ContextMenuContent>
|
||||
<RenameMenuItem />
|
||||
<ContextMenuItem onClick={handleDelete}>
|
||||
<TrashIcon />
|
||||
Move to trash
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
)}
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
|
||||
function RenameMenuItem() {
|
||||
const store = useStore()
|
||||
const target = useAtomValue(contextMenuTargeItemsAtom)
|
||||
const setItemBeingRenamed = useSetAtom(itemBeingRenamedAtom)
|
||||
|
||||
const handleRename = () => {
|
||||
const selectedItems = store.get(contextMenuTargeItemsAtom)
|
||||
if (selectedItems.length === 1) {
|
||||
// biome-ignore lint/style/noNonNullAssertion: length is checked
|
||||
const selectedItem = selectedItems[0]!
|
||||
setItemBeingRenamed({
|
||||
originalItem: selectedItem,
|
||||
name: selectedItem.doc.name,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Only render if exactly one item is selected
|
||||
if (target.length !== 1) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<ContextMenuItem onClick={handleRename}>
|
||||
<TextCursorInputIcon />
|
||||
Rename
|
||||
</ContextMenuItem>
|
||||
)
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
|
||||
export function DirectoryContentTableSkeleton({ rows = 8 }: { rows?: number }) {
|
||||
return (
|
||||
<div className="overflow-hidden">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="px-4">
|
||||
<TableHead
|
||||
className="first:pl-4 last:pr-4"
|
||||
style={{ width: 24 }}
|
||||
>
|
||||
<Skeleton className="size-4 rounded" />
|
||||
</TableHead>
|
||||
<TableHead
|
||||
className="first:pl-4 last:pr-4"
|
||||
style={{ width: 1000 }}
|
||||
>
|
||||
<Skeleton className="h-4 w-12" />
|
||||
</TableHead>
|
||||
<TableHead className="first:pl-4 last:pr-4">
|
||||
<Skeleton className="h-4 w-8" />
|
||||
</TableHead>
|
||||
<TableHead className="first:pl-4 last:pr-4">
|
||||
<Skeleton className="h-4 w-20" />
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{Array.from({ length: rows }).map((_, index) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: this is static so ok
|
||||
<DirectoryContentTableRowSkeleton key={index} />
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DirectoryContentTableRowSkeleton() {
|
||||
return (
|
||||
<TableRow>
|
||||
<TableCell className="first:pl-4 last:pr-4" style={{ width: 24 }}>
|
||||
<Skeleton className="size-4 rounded" />
|
||||
</TableCell>
|
||||
<TableCell className="first:pl-4 last:pr-4" style={{ width: 1000 }}>
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<Skeleton className="size-4 rounded" />
|
||||
<Skeleton className="h-4 w-32" />
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="first:pl-4 last:pr-4">
|
||||
<Skeleton className="h-4 w-16" />
|
||||
</TableCell>
|
||||
<TableCell className="first:pl-4 last:pr-4">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
@@ -1,411 +0,0 @@
|
||||
import type { Doc } from "@fileone/convex/_generated/dataModel"
|
||||
import {
|
||||
type DirectoryHandle,
|
||||
type FileHandle,
|
||||
type FileSystemHandle,
|
||||
type FileSystemItem,
|
||||
FileType,
|
||||
isSameHandle,
|
||||
newDirectoryHandle,
|
||||
newFileHandle,
|
||||
newFileSystemHandle,
|
||||
} from "@fileone/convex/model/filesystem"
|
||||
import { Link, useNavigate } from "@tanstack/react-router"
|
||||
import {
|
||||
type ColumnDef,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
type Row,
|
||||
type Table as TableType,
|
||||
useReactTable,
|
||||
} from "@tanstack/react-table"
|
||||
import { type PrimitiveAtom, useSetAtom, useStore } from "jotai"
|
||||
import { useContext, useEffect, useMemo, useRef } from "react"
|
||||
import { DirectoryIcon } from "@/components/icons/directory-icon"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
isControlOrCommandKeyActive,
|
||||
keyboardModifierAtom,
|
||||
} from "@/lib/keyboard"
|
||||
import { TextFileIcon } from "../../components/icons/text-file-icon"
|
||||
import { type FileDragInfo, useFileDrop } from "../../files/use-file-drop"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { DirectoryPageContext } from "./context"
|
||||
|
||||
type DirectoryContentTableProps = {
|
||||
filterFn: (item: FileSystemItem) => boolean
|
||||
directoryUrlFn: (directory: Doc<"directories">) => string
|
||||
fileDragInfoAtom: PrimitiveAtom<FileDragInfo | null>
|
||||
onContextMenu: (
|
||||
row: Row<FileSystemItem>,
|
||||
table: TableType<FileSystemItem>,
|
||||
) => void
|
||||
onOpenFile: (file: Doc<"files">) => void
|
||||
}
|
||||
|
||||
function formatFileSize(bytes: number): string {
|
||||
if (bytes === 0) return "0 B"
|
||||
|
||||
const k = 1024
|
||||
const sizes = ["B", "KB", "MB", "GB", "TB", "PB"]
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
|
||||
return `${parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`
|
||||
}
|
||||
|
||||
function useTableColumns(
|
||||
onOpenFile: (file: Doc<"files">) => void,
|
||||
directoryUrlFn: (directory: Doc<"directories">) => string,
|
||||
): ColumnDef<FileSystemItem>[] {
|
||||
return useMemo(
|
||||
() => [
|
||||
{
|
||||
id: "select",
|
||||
header: ({ table }) => (
|
||||
<Checkbox
|
||||
checked={table.getIsAllPageRowsSelected()}
|
||||
onCheckedChange={(value) => {
|
||||
table.toggleAllPageRowsSelected(!!value)
|
||||
}}
|
||||
aria-label="Select all"
|
||||
/>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
checked={row.getIsSelected()}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
}}
|
||||
onCheckedChange={row.getToggleSelectedHandler()}
|
||||
aria-label="Select row"
|
||||
/>
|
||||
),
|
||||
enableSorting: false,
|
||||
enableHiding: false,
|
||||
size: 24,
|
||||
},
|
||||
{
|
||||
header: "Name",
|
||||
accessorKey: "doc.name",
|
||||
cell: ({ row }) => {
|
||||
switch (row.original.kind) {
|
||||
case FileType.File:
|
||||
return (
|
||||
<FileNameCell
|
||||
file={row.original.doc}
|
||||
onOpenFile={onOpenFile}
|
||||
/>
|
||||
)
|
||||
case FileType.Directory:
|
||||
return (
|
||||
<DirectoryNameCell
|
||||
directory={row.original.doc}
|
||||
directoryUrlFn={directoryUrlFn}
|
||||
/>
|
||||
)
|
||||
}
|
||||
},
|
||||
size: 1000,
|
||||
},
|
||||
{
|
||||
header: "Size",
|
||||
accessorKey: "size",
|
||||
cell: ({ row }) => {
|
||||
switch (row.original.kind) {
|
||||
case FileType.File:
|
||||
return (
|
||||
<div>
|
||||
{formatFileSize(row.original.doc.size)}
|
||||
</div>
|
||||
)
|
||||
case FileType.Directory:
|
||||
return <div className="font-mono">-</div>
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
header: "Created At",
|
||||
accessorKey: "createdAt",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div>
|
||||
{new Date(
|
||||
row.original.doc.createdAt,
|
||||
).toLocaleString()}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
],
|
||||
[onOpenFile, directoryUrlFn],
|
||||
)
|
||||
}
|
||||
|
||||
export function DirectoryContentTable({
|
||||
filterFn,
|
||||
directoryUrlFn,
|
||||
onContextMenu,
|
||||
fileDragInfoAtom,
|
||||
onOpenFile,
|
||||
}: DirectoryContentTableProps) {
|
||||
const { directoryContent } = useContext(DirectoryPageContext)
|
||||
const store = useStore()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const table = useReactTable({
|
||||
data: directoryContent || [],
|
||||
columns: useTableColumns(onOpenFile, directoryUrlFn),
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
enableRowSelection: true,
|
||||
enableGlobalFilter: true,
|
||||
globalFilterFn: (row, _columnId, _filterValue, _addMeta) =>
|
||||
filterFn(row.original),
|
||||
getRowId: (row) => row.doc._id,
|
||||
})
|
||||
|
||||
useEffect(
|
||||
function escapeToClearSelections() {
|
||||
const handleEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
table.setRowSelection({})
|
||||
}
|
||||
}
|
||||
window.addEventListener("keydown", handleEscape)
|
||||
return () => window.removeEventListener("keydown", handleEscape)
|
||||
},
|
||||
[table.setRowSelection],
|
||||
)
|
||||
|
||||
const handleRowContextMenu = (
|
||||
row: Row<FileSystemItem>,
|
||||
_event: React.MouseEvent,
|
||||
) => {
|
||||
if (!row.getIsSelected()) {
|
||||
selectRow(row)
|
||||
}
|
||||
onContextMenu(row, table)
|
||||
}
|
||||
|
||||
const selectRow = (row: Row<FileSystemItem>) => {
|
||||
const keyboardModifiers = store.get(keyboardModifierAtom)
|
||||
const isMultiSelectMode = isControlOrCommandKeyActive(keyboardModifiers)
|
||||
const isRowSelected = row.getIsSelected()
|
||||
if (isRowSelected && isMultiSelectMode) {
|
||||
row.toggleSelected(false)
|
||||
} else if (isRowSelected && !isMultiSelectMode) {
|
||||
table.setRowSelection({
|
||||
[row.id]: true,
|
||||
})
|
||||
row.toggleSelected(true)
|
||||
} else if (!isRowSelected) {
|
||||
if (isMultiSelectMode) {
|
||||
row.toggleSelected(true)
|
||||
} else {
|
||||
table.setRowSelection({
|
||||
[row.id]: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleRowDoubleClick = (row: Row<FileSystemItem>) => {
|
||||
if (row.original.kind === FileType.Directory) {
|
||||
navigate({
|
||||
to: `/directories/${row.original.doc._id}`,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="overflow-hidden">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow className="px-4" key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => (
|
||||
<TableHead
|
||||
className="first:pl-4 last:pr-4"
|
||||
key={header.id}
|
||||
style={{ width: header.getSize() }}
|
||||
>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map((row) => (
|
||||
<FileItemRow
|
||||
key={row.id}
|
||||
table={table}
|
||||
row={row}
|
||||
onClick={() => selectRow(row)}
|
||||
fileDragInfoAtom={fileDragInfoAtom}
|
||||
onContextMenu={(e) =>
|
||||
handleRowContextMenu(row, e)
|
||||
}
|
||||
onDoubleClick={() => {
|
||||
handleRowDoubleClick(row)
|
||||
}}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<NoResultsRow />
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function NoResultsRow() {
|
||||
return (
|
||||
<TableRow className="hover:bg-transparent">
|
||||
<TableCell colSpan={4} className="text-center">
|
||||
No results.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function FileItemRow({
|
||||
table,
|
||||
row,
|
||||
onClick,
|
||||
onContextMenu,
|
||||
onDoubleClick,
|
||||
fileDragInfoAtom,
|
||||
}: {
|
||||
table: TableType<FileSystemItem>
|
||||
row: Row<FileSystemItem>
|
||||
onClick: () => void
|
||||
onContextMenu: (e: React.MouseEvent) => void
|
||||
onDoubleClick: () => void
|
||||
fileDragInfoAtom: PrimitiveAtom<FileDragInfo | null>
|
||||
}) {
|
||||
const ref = useRef<HTMLTableRowElement>(null)
|
||||
const setFileDragInfo = useSetAtom(fileDragInfoAtom)
|
||||
|
||||
const { isDraggedOver, dropHandlers } = useFileDrop({
|
||||
destItem:
|
||||
row.original.kind === FileType.Directory
|
||||
? newDirectoryHandle(row.original.doc._id)
|
||||
: null,
|
||||
dragInfoAtom: fileDragInfoAtom,
|
||||
})
|
||||
|
||||
const handleDragStart = (_e: React.DragEvent) => {
|
||||
let source: DirectoryHandle | FileHandle
|
||||
switch (row.original.kind) {
|
||||
case FileType.File:
|
||||
source = newFileHandle(row.original.doc._id)
|
||||
break
|
||||
case FileType.Directory:
|
||||
source = newDirectoryHandle(row.original.doc._id)
|
||||
break
|
||||
}
|
||||
|
||||
let draggedItems: FileSystemHandle[]
|
||||
// drag all selections, but only if the currently dragged row is also selected
|
||||
if (row.getIsSelected()) {
|
||||
draggedItems = table
|
||||
.getSelectedRowModel()
|
||||
.rows.map((row) => newFileSystemHandle(row.original))
|
||||
if (!draggedItems.some((item) => isSameHandle(item, source))) {
|
||||
draggedItems.push(source)
|
||||
}
|
||||
} else {
|
||||
draggedItems = [source]
|
||||
}
|
||||
|
||||
setFileDragInfo({
|
||||
source,
|
||||
items: draggedItems,
|
||||
})
|
||||
}
|
||||
|
||||
const handleDragEnd = () => {
|
||||
setFileDragInfo(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
draggable
|
||||
ref={ref}
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && "selected"}
|
||||
onClick={onClick}
|
||||
onDoubleClick={onDoubleClick}
|
||||
onContextMenu={onContextMenu}
|
||||
onDragStart={handleDragStart}
|
||||
onDragEnd={handleDragEnd}
|
||||
{...dropHandlers}
|
||||
className={cn({ "bg-muted": isDraggedOver })}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell
|
||||
className="first:pl-4 last:pr-4"
|
||||
key={cell.id}
|
||||
style={{ width: cell.column.getSize() }}
|
||||
>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function DirectoryNameCell({
|
||||
directory,
|
||||
directoryUrlFn,
|
||||
}: {
|
||||
directory: Doc<"directories">
|
||||
directoryUrlFn: (directory: Doc<"directories">) => string
|
||||
}) {
|
||||
return (
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<DirectoryIcon className="size-4" />
|
||||
<Link className="hover:underline" to={directoryUrlFn(directory)}>
|
||||
{directory.name}
|
||||
</Link>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FileNameCell({
|
||||
file,
|
||||
onOpenFile,
|
||||
}: {
|
||||
file: Doc<"files">
|
||||
onOpenFile: (file: Doc<"files">) => void
|
||||
}) {
|
||||
return (
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<TextFileIcon className="size-4" />
|
||||
<button
|
||||
type="button"
|
||||
className="hover:underline cursor-pointer"
|
||||
onClick={() => {
|
||||
onOpenFile(file)
|
||||
}}
|
||||
>
|
||||
{file.name}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
Breadcrumb,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbList,
|
||||
} from "../../components/ui/breadcrumb"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { DirectoryContentTableSkeleton } from "./directory-content-table-skeleton"
|
||||
|
||||
export function DirectoryPageSkeleton() {
|
||||
return (
|
||||
<>
|
||||
<header className="flex py-1 shrink-0 items-center gap-2 border-b px-4 w-full">
|
||||
<BreadcrumbSkeleton />
|
||||
<div className="ml-auto flex flex-row gap-2">
|
||||
<Button size="sm" type="button" variant="outline" disabled>
|
||||
<Skeleton className="size-4 rounded" />
|
||||
<Skeleton className="h-4 w-8" />
|
||||
<Skeleton className="size-4 rounded" />
|
||||
</Button>
|
||||
<Button size="sm" type="button" disabled>
|
||||
<Skeleton className="size-4 rounded" />
|
||||
<Skeleton className="h-4 w-16" />
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
<div className="w-full">
|
||||
<DirectoryContentTableSkeleton />
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbSkeleton() {
|
||||
return (
|
||||
<Breadcrumb>
|
||||
<BreadcrumbList>
|
||||
<BreadcrumbItem>
|
||||
<Skeleton className="h-4 w-16" />
|
||||
</BreadcrumbItem>
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
)
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
import type { Id } from "@fileone/convex/_generated/dataModel"
|
||||
import type {
|
||||
DirectoryHandle,
|
||||
DirectoryPathComponent,
|
||||
} from "@fileone/convex/model/filesystem"
|
||||
import { Link } from "@tanstack/react-router"
|
||||
import { Fragment, useContext } from "react"
|
||||
import {
|
||||
Breadcrumb,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbLink,
|
||||
BreadcrumbList,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
} from "../../components/ui/breadcrumb"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "../../components/ui/tooltip"
|
||||
import { useFileDrop } from "../../files/use-file-drop"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { DirectoryPageContext } from "./context"
|
||||
import { dragInfoAtom } from "./state"
|
||||
|
||||
export function FilePathBreadcrumb({
|
||||
rootLabel,
|
||||
directoryUrlFn,
|
||||
}: {
|
||||
rootLabel: string
|
||||
directoryUrlFn: (directory: Id<"directories">) => string
|
||||
}) {
|
||||
const { rootDirectory, directory } = useContext(DirectoryPageContext)
|
||||
|
||||
const breadcrumbItems: React.ReactNode[] = []
|
||||
for (let i = 1; i < directory.path.length - 1; i++) {
|
||||
breadcrumbItems.push(
|
||||
<Fragment key={directory.path[i]?.handle.id}>
|
||||
<BreadcrumbSeparator />
|
||||
<FilePathBreadcrumbItem
|
||||
component={directory.path[i]!}
|
||||
rootLabel={rootLabel}
|
||||
directoryUrlFn={directoryUrlFn}
|
||||
/>
|
||||
</Fragment>,
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Breadcrumb>
|
||||
<BreadcrumbList>
|
||||
{rootDirectory._id === directory._id ? (
|
||||
<BreadcrumbItem>
|
||||
<BreadcrumbPage>{rootLabel}</BreadcrumbPage>
|
||||
</BreadcrumbItem>
|
||||
) : (
|
||||
<FilePathBreadcrumbItem
|
||||
component={directory.path[0]!}
|
||||
rootLabel={rootLabel}
|
||||
directoryUrlFn={directoryUrlFn}
|
||||
/>
|
||||
)}
|
||||
{breadcrumbItems}
|
||||
<BreadcrumbSeparator />
|
||||
<BreadcrumbItem>
|
||||
<BreadcrumbPage>{directory.name}</BreadcrumbPage>{" "}
|
||||
</BreadcrumbItem>
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
)
|
||||
}
|
||||
|
||||
function FilePathBreadcrumbItem({
|
||||
component,
|
||||
rootLabel,
|
||||
directoryUrlFn,
|
||||
}: {
|
||||
component: DirectoryPathComponent
|
||||
rootLabel: string
|
||||
directoryUrlFn: (directory: Id<"directories">) => string
|
||||
}) {
|
||||
const { isDraggedOver, dropHandlers } = useFileDrop({
|
||||
destItem: component.handle as DirectoryHandle,
|
||||
dragInfoAtom,
|
||||
})
|
||||
|
||||
const dirName = component.name || rootLabel
|
||||
|
||||
return (
|
||||
<Tooltip open={isDraggedOver}>
|
||||
<TooltipTrigger asChild>
|
||||
<BreadcrumbItem
|
||||
className={cn({ "bg-muted": isDraggedOver })}
|
||||
{...dropHandlers}
|
||||
>
|
||||
<BreadcrumbLink asChild>
|
||||
<Link to={directoryUrlFn(component.handle.id)}>
|
||||
{dirName}
|
||||
</Link>
|
||||
</BreadcrumbLink>
|
||||
</BreadcrumbItem>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Move to {dirName}</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import type { Id } from "@fileone/convex/_generated/dataModel"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { useMutation as useContextMutation } from "convex/react"
|
||||
import { useId } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
|
||||
export function NewDirectoryDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
directoryId,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
directoryId: Id<"directories">
|
||||
}) {
|
||||
const formId = useId()
|
||||
|
||||
const { mutate: createDirectory, isPending: isCreating } = useMutation({
|
||||
mutationFn: useContextMutation(api.files.createDirectory),
|
||||
onSuccess: () => {
|
||||
onOpenChange(false)
|
||||
toast.success("Directory created successfully")
|
||||
},
|
||||
})
|
||||
|
||||
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
|
||||
const formData = new FormData(event.currentTarget)
|
||||
const name = formData.get("directoryName") as string
|
||||
|
||||
if (name) {
|
||||
createDirectory({ name, directoryId })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>New Directory</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form id={formId} onSubmit={onSubmit}>
|
||||
<Input name="directoryName" />
|
||||
</form>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button loading={isCreating} variant="outline">
|
||||
<span>Cancel</span>
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button loading={isCreating} type="submit" form={formId}>
|
||||
<span>Create</span>
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import { type FileSystemItem, FileType } from "@fileone/convex/model/filesystem"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { useMutation as useContextMutation } from "convex/react"
|
||||
import { useId } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
|
||||
type RenameFileDialogProps = {
|
||||
item: FileSystemItem
|
||||
onRenameSuccess: () => void
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export function RenameFileDialog({
|
||||
item,
|
||||
onRenameSuccess,
|
||||
onClose,
|
||||
}: RenameFileDialogProps) {
|
||||
const formId = useId()
|
||||
|
||||
const { mutate: renameFile, isPending: isRenaming } = useMutation({
|
||||
mutationFn: useContextMutation(api.files.renameFile),
|
||||
onSuccess: () => {
|
||||
onRenameSuccess()
|
||||
},
|
||||
})
|
||||
|
||||
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
|
||||
const formData = new FormData(event.currentTarget)
|
||||
const newName = formData.get("itemName") as string
|
||||
|
||||
if (newName) {
|
||||
switch (item.kind) {
|
||||
case FileType.File:
|
||||
renameFile({
|
||||
directoryId: item.doc.directoryId,
|
||||
itemId: item.doc._id,
|
||||
newName,
|
||||
})
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
onClose()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Rename File</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form id={formId} onSubmit={onSubmit}>
|
||||
<RenameFileInput initialValue={item.doc.name} />
|
||||
</form>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button loading={isRenaming} variant="outline">
|
||||
<span>Cancel</span>
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button loading={isRenaming} type="submit" form={formId}>
|
||||
<span>Rename</span>
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function RenameFileInput({ initialValue }: { initialValue: string }) {
|
||||
return <Input defaultValue={initialValue} name="itemName" />
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { DirectoryContentTableSkeleton } from "./directory-content-table-skeleton"
|
||||
import { DirectoryPageSkeleton } from "./directory-page-skeleton"
|
||||
|
||||
export function SkeletonDemo() {
|
||||
const [showPageSkeleton, setShowPageSkeleton] = useState(false)
|
||||
const [showTableSkeleton, setShowTableSkeleton] = useState(false)
|
||||
|
||||
return (
|
||||
<div className="p-4 space-y-4">
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={() => setShowPageSkeleton(!showPageSkeleton)}
|
||||
variant={showPageSkeleton ? "default" : "outline"}
|
||||
>
|
||||
{showPageSkeleton ? "Hide" : "Show"} Page Skeleton
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => setShowTableSkeleton(!showTableSkeleton)}
|
||||
variant={showTableSkeleton ? "default" : "outline"}
|
||||
>
|
||||
{showTableSkeleton ? "Hide" : "Show"} Table Skeleton
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showPageSkeleton && (
|
||||
<div className="border rounded-lg p-4">
|
||||
<h3 className="text-lg font-semibold mb-4">
|
||||
Directory Page Skeleton
|
||||
</h3>
|
||||
<DirectoryPageSkeleton />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showTableSkeleton && (
|
||||
<div className="border rounded-lg p-4">
|
||||
<h3 className="text-lg font-semibold mb-4">
|
||||
Directory Content Table Skeleton
|
||||
</h3>
|
||||
<DirectoryContentTableSkeleton rows={5} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import type { Doc, Id } from "@fileone/convex/_generated/dataModel"
|
||||
import type { FileSystemItem, FileType } from "@fileone/convex/model/filesystem"
|
||||
import type { RowSelectionState } from "@tanstack/react-table"
|
||||
import { atom } from "jotai"
|
||||
import type { FileDragInfo } from "../../files/use-file-drop"
|
||||
|
||||
export const contextMenuTargeItemsAtom = atom<FileSystemItem[]>([])
|
||||
export const optimisticDeletedItemsAtom = atom(
|
||||
new Set<Id<"files"> | Id<"directories">>(),
|
||||
)
|
||||
|
||||
export const selectedFileRowsAtom = atom<RowSelectionState>({})
|
||||
|
||||
export const itemBeingRenamedAtom = atom<{
|
||||
originalItem: FileSystemItem
|
||||
name: string
|
||||
} | null>(null)
|
||||
|
||||
export const openedFileAtom = atom<Doc<"files"> | null>(null)
|
||||
|
||||
export const dragInfoAtom = atom<FileDragInfo | null>(null)
|
||||
@@ -1,34 +0,0 @@
|
||||
/**
|
||||
* This file is the entry point for the React app, it sets up the root
|
||||
* element and renders the App component to the DOM.
|
||||
*
|
||||
* It is included in `src/index.html`.
|
||||
*/
|
||||
|
||||
import { createRouter, RouterProvider } from "@tanstack/react-router"
|
||||
import { StrictMode } from "react"
|
||||
import { createRoot } from "react-dom/client"
|
||||
import { ThemeProvider } from "@/components/theme-provider"
|
||||
// Import the generated route tree
|
||||
import { routeTree } from "./routeTree.gen"
|
||||
|
||||
// Create a new router instance
|
||||
const router = createRouter({ routeTree })
|
||||
|
||||
const elem = document.getElementById("root")!
|
||||
const app = (
|
||||
<StrictMode>
|
||||
<ThemeProvider defaultTheme="system" storageKey="fileone-ui-theme">
|
||||
<RouterProvider router={router} />
|
||||
</ThemeProvider>
|
||||
</StrictMode>
|
||||
)
|
||||
|
||||
if (import.meta.hot) {
|
||||
// With hot module reloading, `import.meta.hot.data` is persisted.
|
||||
const root = (import.meta.hot.data.root ??= createRoot(elem))
|
||||
root.render(app)
|
||||
} else {
|
||||
// The hot module reloading API is not available in production.
|
||||
createRoot(elem).render(app)
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
import { useAtomValue } from "jotai"
|
||||
import { CircleAlertIcon, XIcon } from "lucide-react"
|
||||
import type React from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Progress } from "@/components/ui/progress"
|
||||
import { Tooltip } from "@/components/ui/tooltip"
|
||||
import { FileUploadStatusKind, fileUploadStatusAtomFamily } from "./store"
|
||||
import type { PickedFile } from "./upload-file-dialog"
|
||||
|
||||
export function PickedFileItem({
|
||||
file: pickedFile,
|
||||
onRemove,
|
||||
}: {
|
||||
file: PickedFile
|
||||
onRemove: (file: PickedFile) => void
|
||||
}) {
|
||||
const fileUploadAtom = fileUploadStatusAtomFamily(pickedFile.id)
|
||||
const fileUpload = useAtomValue(fileUploadAtom)
|
||||
console.log("fileUpload", fileUpload)
|
||||
const { file, id } = pickedFile
|
||||
|
||||
let statusIndicator: React.ReactNode
|
||||
if (!fileUpload) {
|
||||
statusIndicator = (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => onRemove(pickedFile)}
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</Button>
|
||||
)
|
||||
} else {
|
||||
switch (fileUpload.kind) {
|
||||
case FileUploadStatusKind.InProgress:
|
||||
statusIndicator = <Progress value={fileUpload.progress * 100} />
|
||||
break
|
||||
case FileUploadStatusKind.Error:
|
||||
statusIndicator = (
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<CircleAlertIcon />
|
||||
</TooltipTrigger>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<li
|
||||
className="pl-3 pr-1 py-0.5 h-8 hover:bg-muted flex justify-between items-center"
|
||||
key={id}
|
||||
>
|
||||
<span>{file.name}</span>
|
||||
{fileUpload ? (
|
||||
<Progress
|
||||
className="max-w-20"
|
||||
value={fileUpload.progress * 100}
|
||||
/>
|
||||
) : (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => onRemove(pickedFile)}
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</Button>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import type { Doc } from "@fileone/convex/_generated/dataModel"
|
||||
import { ImagePreviewDialog } from "./image-preview-dialog"
|
||||
|
||||
export function FilePreviewDialog({
|
||||
file,
|
||||
onClose,
|
||||
}: {
|
||||
file: Doc<"files">
|
||||
onClose: () => void
|
||||
}) {
|
||||
if (!file) return null
|
||||
|
||||
switch (file.mimeType) {
|
||||
case "image/jpeg":
|
||||
case "image/png":
|
||||
case "image/gif":
|
||||
return <ImagePreviewDialog file={file} onClose={onClose} />
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -1,422 +0,0 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import type { Doc } from "@fileone/convex/_generated/dataModel"
|
||||
import type { DirectoryItem } from "@fileone/convex/model/directories"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { Link } from "@tanstack/react-router"
|
||||
import {
|
||||
type ColumnDef,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
type Row,
|
||||
useReactTable,
|
||||
} from "@tanstack/react-table"
|
||||
import { useMutation as useContextMutation, useQuery } from "convex/react"
|
||||
import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai"
|
||||
import { CheckIcon, TextCursorInputIcon, TrashIcon, XIcon } from "lucide-react"
|
||||
import { useEffect, useId, useRef } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { DirectoryIcon } from "@/components/icons/directory-icon"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuTrigger,
|
||||
} from "@/components/ui/context-menu"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import { TextFileIcon } from "../components/icons/text-file-icon"
|
||||
import { Button } from "../components/ui/button"
|
||||
import { LoadingSpinner } from "../components/ui/loading-spinner"
|
||||
import { withDefaultOnError } from "../lib/error"
|
||||
import { cn } from "../lib/utils"
|
||||
import {
|
||||
contextMenuTargeItemAtom,
|
||||
itemBeingRenamedAtom,
|
||||
newItemKindAtom,
|
||||
optimisticDeletedItemsAtom,
|
||||
} from "./state"
|
||||
|
||||
function formatFileSize(bytes: number): string {
|
||||
if (bytes === 0) return "0 B"
|
||||
|
||||
const k = 1024
|
||||
const sizes = ["B", "KB", "MB", "GB", "TB", "PB"]
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
|
||||
return `${parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`
|
||||
}
|
||||
|
||||
const columns: ColumnDef<DirectoryItem>[] = [
|
||||
{
|
||||
id: "select",
|
||||
header: ({ table }) => (
|
||||
<Checkbox
|
||||
checked={table.getIsAllPageRowsSelected()}
|
||||
onCheckedChange={(value) =>
|
||||
table.toggleAllPageRowsSelected(!!value)
|
||||
}
|
||||
aria-label="Select all"
|
||||
/>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
checked={row.getIsSelected()}
|
||||
onCheckedChange={row.getToggleSelectedHandler()}
|
||||
aria-label="Select row"
|
||||
/>
|
||||
),
|
||||
enableSorting: false,
|
||||
enableHiding: false,
|
||||
size: 24,
|
||||
},
|
||||
{
|
||||
header: "Name",
|
||||
accessorKey: "doc.name",
|
||||
cell: ({ row }) => {
|
||||
switch (row.original.kind) {
|
||||
case "file":
|
||||
return <FileNameCell initialName={row.original.doc.name} />
|
||||
case "directory":
|
||||
return <DirectoryNameCell directory={row.original.doc} />
|
||||
}
|
||||
},
|
||||
size: 1000,
|
||||
},
|
||||
{
|
||||
header: "Size",
|
||||
accessorKey: "size",
|
||||
cell: ({ row }) => {
|
||||
switch (row.original.kind) {
|
||||
case "file":
|
||||
return <div>{formatFileSize(row.original.doc.size)}</div>
|
||||
case "directory":
|
||||
return <div className="font-mono">-</div>
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
header: "Created At",
|
||||
accessorKey: "createdAt",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div>
|
||||
{new Date(row.original.doc.createdAt).toLocaleString()}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
export function FileTable({ path }: { path: string }) {
|
||||
return (
|
||||
<FileTableContextMenu>
|
||||
<div className="w-full">
|
||||
<FileTableContent path={path} />
|
||||
</div>
|
||||
</FileTableContextMenu>
|
||||
)
|
||||
}
|
||||
|
||||
export function FileTableContextMenu({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const store = useStore()
|
||||
const target = useAtomValue(contextMenuTargeItemAtom)
|
||||
const setOptimisticDeletedItems = useSetAtom(optimisticDeletedItemsAtom)
|
||||
const moveToTrashMutation = useContextMutation(api.files.moveToTrash)
|
||||
const setItemBeingRenamed = useSetAtom(itemBeingRenamedAtom)
|
||||
const { mutate: moveToTrash } = useMutation({
|
||||
mutationFn: moveToTrashMutation,
|
||||
onMutate: ({ itemId }) => {
|
||||
setOptimisticDeletedItems((prev) => new Set([...prev, itemId]))
|
||||
},
|
||||
onSuccess: (itemId) => {
|
||||
setOptimisticDeletedItems((prev) => {
|
||||
const newSet = new Set(prev)
|
||||
newSet.delete(itemId)
|
||||
return newSet
|
||||
})
|
||||
toast.success("Moved to trash")
|
||||
},
|
||||
})
|
||||
|
||||
const handleRename = () => {
|
||||
const selectedItem = store.get(contextMenuTargeItemAtom)
|
||||
if (selectedItem) {
|
||||
setItemBeingRenamed({
|
||||
kind: selectedItem.kind,
|
||||
originalItem: selectedItem,
|
||||
name: selectedItem.doc.name,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = () => {
|
||||
const selectedItem = store.get(contextMenuTargeItemAtom)
|
||||
if (selectedItem) {
|
||||
moveToTrash({
|
||||
kind: selectedItem.kind,
|
||||
itemId: selectedItem.doc._id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
|
||||
{target && (
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onClick={handleRename}>
|
||||
<TextCursorInputIcon />
|
||||
Rename
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={handleDelete}>
|
||||
<TrashIcon />
|
||||
Move to trash
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
)}
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
|
||||
export function FileTableContent({ path }: { path: string }) {
|
||||
const directory = useQuery(api.files.fetchDirectoryContent, { path })
|
||||
const optimisticDeletedItems = useAtomValue(optimisticDeletedItemsAtom)
|
||||
const setContextMenuTargetItem = useSetAtom(contextMenuTargeItemAtom)
|
||||
const store = useStore()
|
||||
|
||||
const handleRowContextMenu = (
|
||||
row: Row<DirectoryItem>,
|
||||
_event: React.MouseEvent,
|
||||
) => {
|
||||
const target = store.get(contextMenuTargeItemAtom)
|
||||
if (target === row.original) {
|
||||
setContextMenuTargetItem(null)
|
||||
} else {
|
||||
selectRow(row)
|
||||
setContextMenuTargetItem(row.original)
|
||||
}
|
||||
}
|
||||
|
||||
const table = useReactTable({
|
||||
data: directory || [],
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
enableRowSelection: true,
|
||||
enableGlobalFilter: true,
|
||||
globalFilterFn: (row, _columnId, _filterValue, _addMeta) => {
|
||||
return !optimisticDeletedItems.has(row.original.doc._id)
|
||||
},
|
||||
getRowId: (row) => row.doc._id,
|
||||
})
|
||||
|
||||
const selectRow = (row: Row<DirectoryItem>) => {
|
||||
console.log("row.getIsSelected()", row.getIsSelected())
|
||||
if (!row.getIsSelected()) {
|
||||
table.toggleAllPageRowsSelected(false)
|
||||
row.toggleSelected(true)
|
||||
}
|
||||
}
|
||||
|
||||
if (!directory) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="overflow-hidden">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow className="px-4" key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => (
|
||||
<TableHead
|
||||
className="first:pl-4 last:pr-4"
|
||||
key={header.id}
|
||||
style={{ width: header.getSize() }}
|
||||
>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && "selected"}
|
||||
onClick={() => {
|
||||
selectRow(row)
|
||||
}}
|
||||
onContextMenu={(e) => {
|
||||
handleRowContextMenu(row, e)
|
||||
}}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell
|
||||
className="first:pl-4 last:pr-4"
|
||||
key={cell.id}
|
||||
style={{ width: cell.column.getSize() }}
|
||||
>
|
||||
{flexRender(
|
||||
cell.column.columnDef.cell,
|
||||
cell.getContext(),
|
||||
)}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<NoResultsRow />
|
||||
)}
|
||||
<NewItemRow />
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function NoResultsRow() {
|
||||
const newItemKind = useAtomValue(newItemKindAtom)
|
||||
if (newItemKind) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<TableRow>
|
||||
<TableCell colSpan={columns.length} className="text-center">
|
||||
No results.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function NewItemRow() {
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const newItemFormId = useId()
|
||||
const [newItemKind, setNewItemKind] = useAtom(newItemKindAtom)
|
||||
const { mutate: createDirectory, isPending } = useMutation({
|
||||
mutationFn: useContextMutation(api.files.createDirectory),
|
||||
onSuccess: () => {
|
||||
setNewItemKind(null)
|
||||
},
|
||||
onError: withDefaultOnError(() => {
|
||||
setTimeout(() => {
|
||||
inputRef.current?.focus()
|
||||
}, 1)
|
||||
}),
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (newItemKind) {
|
||||
setTimeout(() => {
|
||||
inputRef.current?.focus()
|
||||
}, 1)
|
||||
}
|
||||
}, [newItemKind])
|
||||
|
||||
if (!newItemKind) {
|
||||
return null
|
||||
}
|
||||
|
||||
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
|
||||
const formData = new FormData(event.currentTarget)
|
||||
const itemName = formData.get("itemName") as string
|
||||
|
||||
if (itemName) {
|
||||
createDirectory({ name: itemName })
|
||||
} else {
|
||||
toast.error("Please enter a name.")
|
||||
}
|
||||
}
|
||||
|
||||
const clearNewItemKind = () => {
|
||||
// setItemBeingAdded(null)
|
||||
setNewItemKind(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<TableRow className={cn("align-middle", { "opacity-50": isPending })}>
|
||||
<TableCell />
|
||||
<TableCell className="p-0">
|
||||
<div className="flex items-center gap-2 px-2 py-1 h-full">
|
||||
{isPending ? (
|
||||
<LoadingSpinner className="size-6" />
|
||||
) : (
|
||||
<DirectoryIcon />
|
||||
)}
|
||||
<form
|
||||
className="w-full"
|
||||
id={newItemFormId}
|
||||
onSubmit={onSubmit}
|
||||
>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
name="itemName"
|
||||
defaultValue={newItemKind}
|
||||
disabled={isPending}
|
||||
className="w-full h-8 px-2 bg-transparent border border-input rounded-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary"
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell />
|
||||
<TableCell align="right" className="space-x-2 p-1">
|
||||
{!isPending ? (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
form={newItemFormId}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={clearNewItemKind}
|
||||
>
|
||||
<XIcon />
|
||||
</Button>
|
||||
<Button type="submit" form={newItemFormId} size="icon">
|
||||
<CheckIcon />
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function DirectoryNameCell({ directory }: { directory: Doc<"directories"> }) {
|
||||
return (
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<DirectoryIcon className="size-4" />
|
||||
<Link className="hover:underline" to={`/files/${directory.path}`}>
|
||||
{directory.name}
|
||||
</Link>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FileNameCell({ initialName }: { initialName: string }) {
|
||||
return (
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<TextFileIcon className="size-4" />
|
||||
{initialName}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import { baseName, splitPath } from "@fileone/path"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { Link } from "@tanstack/react-router"
|
||||
import { useMutation as useConvexMutation } from "convex/react"
|
||||
import { useSetAtom } from "jotai"
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
Loader2Icon,
|
||||
PlusIcon,
|
||||
UploadCloudIcon,
|
||||
} from "lucide-react"
|
||||
import { type ChangeEvent, Fragment, useRef } from "react"
|
||||
import { toast } from "sonner"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { DirectoryIcon } from "../components/icons/directory-icon"
|
||||
import { TextFileIcon } from "../components/icons/text-file-icon"
|
||||
import {
|
||||
Breadcrumb,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbLink,
|
||||
BreadcrumbList,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
} from "../components/ui/breadcrumb"
|
||||
import { Button } from "../components/ui/button"
|
||||
import { FileTable } from "./file-table"
|
||||
import { RenameFileDialog } from "./rename-file-dialog"
|
||||
import { newItemKindAtom } from "./state"
|
||||
|
||||
export function FilesPage({ path }: { path: string }) {
|
||||
return (
|
||||
<>
|
||||
<header className="flex py-1 shrink-0 items-center gap-2 border-b px-4 w-full">
|
||||
<FilePathBreadcrumb path={path} />
|
||||
<div className="ml-auto flex flex-row gap-2">
|
||||
<NewDirectoryItemDropdown />
|
||||
<UploadFileButton />
|
||||
</div>
|
||||
</header>
|
||||
<div className="w-full">
|
||||
<FileTable path={path} />
|
||||
</div>
|
||||
<RenameFileDialog />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function FilePathBreadcrumb({ path }: { path: string }) {
|
||||
const pathComponents = splitPath(path)
|
||||
const base = baseName(path)
|
||||
return (
|
||||
<Breadcrumb>
|
||||
<BreadcrumbList>
|
||||
<BreadcrumbItem>
|
||||
<BreadcrumbLink asChild>
|
||||
<Link to="/files">All Files</Link>
|
||||
</BreadcrumbLink>
|
||||
</BreadcrumbItem>
|
||||
{pathComponents.map((p) => (
|
||||
<Fragment key={p}>
|
||||
<BreadcrumbSeparator />
|
||||
{p === base ? (
|
||||
<BreadcrumbPage>{p}</BreadcrumbPage>
|
||||
) : (
|
||||
<BreadcrumbItem>
|
||||
<BreadcrumbLink asChild>
|
||||
<Link to={`/files/${p}`}>{p}</Link>
|
||||
</BreadcrumbLink>
|
||||
</BreadcrumbItem>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
)
|
||||
}
|
||||
|
||||
// tags: upload, uploadfile, uploadfilebutton, fileupload, fileuploadbutton
|
||||
function UploadFileButton() {
|
||||
const generateUploadUrl = useConvexMutation(api.files.generateUploadUrl)
|
||||
const saveFile = useConvexMutation(api.files.saveFile)
|
||||
const { mutate: uploadFile, isPending: isUploading } = useMutation({
|
||||
mutationFn: async (file: File) => {
|
||||
const uploadUrl = await generateUploadUrl()
|
||||
const uploadResult = await fetch(uploadUrl, {
|
||||
method: "POST",
|
||||
body: file,
|
||||
headers: {
|
||||
"Content-Type": file.type,
|
||||
},
|
||||
})
|
||||
const { storageId } = await uploadResult.json()
|
||||
|
||||
await saveFile({
|
||||
storageId,
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
mimeType: file.type,
|
||||
})
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success("File uploaded successfully.")
|
||||
},
|
||||
})
|
||||
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const handleClick = () => {
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
|
||||
const onFileUpload = async (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) {
|
||||
uploadFile(file)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<input
|
||||
hidden
|
||||
onChange={onFileUpload}
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
name="files"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={handleClick}
|
||||
disabled={isUploading}
|
||||
>
|
||||
{isUploading ? (
|
||||
<Loader2Icon className="animate-spin size-4" />
|
||||
) : (
|
||||
<UploadCloudIcon className="size-4" />
|
||||
)}
|
||||
{isUploading ? "Uploading" : "Upload File"}
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function NewDirectoryItemDropdown() {
|
||||
const setNewItemKind = useSetAtom(newItemKindAtom)
|
||||
|
||||
const addNewDirectory = () => {
|
||||
setNewItemKind("directory")
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button size="sm" type="button" variant="outline">
|
||||
<PlusIcon className="size-4" />
|
||||
New
|
||||
<ChevronDownIcon className="pl-1 size-4 shrink-0" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem>
|
||||
<TextFileIcon />
|
||||
Text file
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={addNewDirectory}>
|
||||
<DirectoryIcon />
|
||||
Directory
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import type { Doc } from "@fileone/convex/_generated/dataModel"
|
||||
import { DialogTitle } from "@radix-ui/react-dialog"
|
||||
import { useQuery as useConvexQuery } from "convex/react"
|
||||
import { atom, useAtom, useAtomValue, useSetAtom } from "jotai"
|
||||
import {
|
||||
DownloadIcon,
|
||||
Maximize2Icon,
|
||||
Minimize2Icon,
|
||||
XIcon,
|
||||
ZoomInIcon,
|
||||
ZoomOutIcon,
|
||||
} from "lucide-react"
|
||||
import { useEffect, useRef } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
} from "@/components/ui/dialog"
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner"
|
||||
|
||||
const zoomLevelAtom = atom(
|
||||
1,
|
||||
(get, set, update: number | ((current: number) => number)) => {
|
||||
const current = get(zoomLevelAtom)
|
||||
console.log("current", current)
|
||||
const newValue = typeof update === "function" ? update(current) : update
|
||||
if (newValue >= 0.1) {
|
||||
set(zoomLevelAtom, newValue)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export function ImagePreviewDialog({
|
||||
file,
|
||||
onClose,
|
||||
}: {
|
||||
file: Doc<"files">
|
||||
onClose: () => void
|
||||
}) {
|
||||
const fileUrl = useConvexQuery(api.filesystem.fetchFileUrl, {
|
||||
fileId: file._id,
|
||||
})
|
||||
const setZoomLevel = useSetAtom(zoomLevelAtom)
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
setZoomLevel(1)
|
||||
},
|
||||
[setZoomLevel],
|
||||
)
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
onClose()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogOverlay className="flex items-center justify-center">
|
||||
{!fileUrl ? (
|
||||
<LoadingSpinner className="text-neutral-200 size-10" />
|
||||
) : null}
|
||||
</DialogOverlay>
|
||||
{fileUrl ? <PreviewContent fileUrl={fileUrl} file={file} /> : null}
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function PreviewContent({
|
||||
fileUrl,
|
||||
file,
|
||||
}: {
|
||||
fileUrl: string
|
||||
file: Doc<"files">
|
||||
}) {
|
||||
return (
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
className="p-0 lg:min-w-1/3 gap-0"
|
||||
>
|
||||
<DialogHeader className="overflow-auto border-b border-b-border p-4 flex flex-row items-center justify-between">
|
||||
<DialogTitle className="truncate flex-1">
|
||||
{file.name}
|
||||
</DialogTitle>
|
||||
<div className="flex flex-row items-center space-x-2">
|
||||
<Toolbar fileUrl={fileUrl} file={file} />
|
||||
<Button variant="ghost" size="icon" asChild>
|
||||
<DialogClose>
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogClose>
|
||||
</Button>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
<div className="w-full h-full flex items-center justify-center max-h-[calc(100vh-10rem)] overflow-auto">
|
||||
<ImagePreview fileUrl={fileUrl} file={file} />
|
||||
</div>
|
||||
</DialogContent>
|
||||
)
|
||||
}
|
||||
|
||||
function Toolbar({ fileUrl, file }: { fileUrl: string; file: Doc<"files"> }) {
|
||||
const setZoomLevel = useSetAtom(zoomLevelAtom)
|
||||
const zoomInterval = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (zoomInterval.current) {
|
||||
clearInterval(zoomInterval.current)
|
||||
console.log("clearInterval")
|
||||
zoomInterval.current = null
|
||||
}
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
function startZooming(delta: number) {
|
||||
setZoomLevel((zoom) => zoom + delta)
|
||||
zoomInterval.current = setInterval(() => {
|
||||
setZoomLevel((zoom) => zoom + delta)
|
||||
}, 100)
|
||||
}
|
||||
|
||||
function stopZooming() {
|
||||
if (zoomInterval.current) {
|
||||
clearInterval(zoomInterval.current)
|
||||
zoomInterval.current = null
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-row items-center space-x-2 border-r border-r-border pr-4">
|
||||
<ResetZoomButton />
|
||||
<Button
|
||||
variant="ghost"
|
||||
onMouseDown={() => {
|
||||
startZooming(0.1)
|
||||
}}
|
||||
onMouseLeave={stopZooming}
|
||||
onMouseUp={stopZooming}
|
||||
>
|
||||
<ZoomInIcon />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onMouseDown={() => {
|
||||
startZooming(-0.1)
|
||||
}}
|
||||
onMouseLeave={stopZooming}
|
||||
onMouseUp={stopZooming}
|
||||
>
|
||||
<ZoomOutIcon />
|
||||
</Button>
|
||||
<Button asChild>
|
||||
<a
|
||||
href={fileUrl}
|
||||
download={file.name}
|
||||
target="_blank"
|
||||
className="flex flex-row items-center"
|
||||
>
|
||||
<DownloadIcon />
|
||||
<span className="sr-only md:not-sr-only">Download</span>
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ResetZoomButton() {
|
||||
const [zoomLevel, setZoomLevel] = useAtom(zoomLevelAtom)
|
||||
|
||||
if (zoomLevel === 1) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setZoomLevel(1)
|
||||
}}
|
||||
>
|
||||
{zoomLevel > 1 ? <Minimize2Icon /> : <Maximize2Icon />}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function ImagePreview({
|
||||
fileUrl,
|
||||
file,
|
||||
}: {
|
||||
fileUrl: string
|
||||
file: Doc<"files">
|
||||
}) {
|
||||
const zoomLevel = useAtomValue(zoomLevelAtom)
|
||||
return (
|
||||
<img
|
||||
src={fileUrl}
|
||||
alt={file.name}
|
||||
className="object-contain"
|
||||
style={{ transform: `scale(${zoomLevel})` }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { useMutation as useContextMutation } from "convex/react"
|
||||
import { atom, useAtom, useStore } from "jotai"
|
||||
import { useId } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { itemBeingRenamedAtom } from "./state"
|
||||
|
||||
const fielNameAtom = atom(
|
||||
(get) => get(itemBeingRenamedAtom)?.name,
|
||||
(get, set, newName: string) => {
|
||||
const current = get(itemBeingRenamedAtom)
|
||||
if (current) {
|
||||
set(itemBeingRenamedAtom, {
|
||||
...current,
|
||||
name: newName,
|
||||
})
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export function RenameFileDialog() {
|
||||
const [itemBeingRenamed, setItemBeingRenamed] =
|
||||
useAtom(itemBeingRenamedAtom)
|
||||
const store = useStore()
|
||||
const formId = useId()
|
||||
|
||||
const { mutate: renameFile, isPending: isRenaming } = useMutation({
|
||||
mutationFn: useContextMutation(api.files.renameFile),
|
||||
onSuccess: () => {
|
||||
setItemBeingRenamed(null)
|
||||
toast.success("File renamed successfully")
|
||||
},
|
||||
})
|
||||
|
||||
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
|
||||
const itemBeingRenamed = store.get(itemBeingRenamedAtom)
|
||||
if (itemBeingRenamed) {
|
||||
const formData = new FormData(event.currentTarget)
|
||||
const newName = formData.get("itemName") as string
|
||||
|
||||
if (newName) {
|
||||
switch (itemBeingRenamed.originalItem.kind) {
|
||||
case "file":
|
||||
renameFile({
|
||||
directoryId:
|
||||
itemBeingRenamed.originalItem.doc.directoryId,
|
||||
itemId: itemBeingRenamed.originalItem.doc._id,
|
||||
newName,
|
||||
})
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={itemBeingRenamed !== null}
|
||||
onOpenChange={(open) =>
|
||||
setItemBeingRenamed(open ? itemBeingRenamed : null)
|
||||
}
|
||||
>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Rename File</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form id={formId} onSubmit={onSubmit}>
|
||||
<RenameFileInput />
|
||||
</form>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button loading={isRenaming} variant="outline">
|
||||
<span>Cancel</span>
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button loading={isRenaming} type="submit" form={formId}>
|
||||
<span>Rename</span>
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function RenameFileInput() {
|
||||
const [fileName, setFileName] = useAtom(fielNameAtom)
|
||||
return (
|
||||
<Input
|
||||
value={fileName}
|
||||
name="itemName"
|
||||
onChange={(e) => setFileName(e.target.value)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import type { Id } from "@fileone/convex/_generated/dataModel"
|
||||
import type {
|
||||
DirectoryItem,
|
||||
DirectoryItemKind,
|
||||
} from "@fileone/convex/model/directories"
|
||||
import type { RowSelectionState } from "@tanstack/react-table"
|
||||
import { atom } from "jotai"
|
||||
|
||||
export const contextMenuTargeItemAtom = atom<DirectoryItem | null>(null)
|
||||
export const optimisticDeletedItemsAtom = atom(
|
||||
new Set<Id<"files"> | Id<"directories">>(),
|
||||
)
|
||||
|
||||
export const selectedFileRowsAtom = atom<RowSelectionState>({})
|
||||
|
||||
export const newItemKindAtom = atom<DirectoryItemKind | null>(null)
|
||||
|
||||
export const itemBeingRenamedAtom = atom<{
|
||||
kind: DirectoryItemKind
|
||||
originalItem: DirectoryItem
|
||||
name: string
|
||||
} | null>(null)
|
||||
@@ -1,97 +0,0 @@
|
||||
import { atom } from "jotai"
|
||||
import { atomFamily } from "jotai/utils"
|
||||
|
||||
export enum FileUploadStatusKind {
|
||||
InProgress = "InProgress",
|
||||
Error = "Error",
|
||||
Success = "Success",
|
||||
}
|
||||
|
||||
export type FileUploadInProgress = {
|
||||
kind: FileUploadStatusKind.InProgress
|
||||
progress: number
|
||||
}
|
||||
|
||||
export type FileUploadError = {
|
||||
kind: FileUploadStatusKind.Error
|
||||
error: unknown
|
||||
}
|
||||
|
||||
export type FileUploadSuccess = {
|
||||
kind: FileUploadStatusKind.Success
|
||||
}
|
||||
|
||||
export type FileUploadStatus =
|
||||
| FileUploadInProgress
|
||||
| FileUploadError
|
||||
| FileUploadSuccess
|
||||
|
||||
export const fileUploadStatusesAtom = atom<Record<string, FileUploadStatus>>({})
|
||||
|
||||
export const fileUploadStatusAtomFamily = atomFamily((id: string) =>
|
||||
atom(
|
||||
(get) => get(fileUploadStatusesAtom)[id],
|
||||
(get, set, status: FileUploadStatus) => {
|
||||
const fileUploads = { ...get(fileUploadStatusesAtom) }
|
||||
fileUploads[id] = status
|
||||
set(fileUploadStatusesAtom, fileUploads)
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
export const clearFileUploadStatusesAtom = atom(
|
||||
null,
|
||||
(get, set, ids: string[]) => {
|
||||
const fileUploads = { ...get(fileUploadStatusesAtom) }
|
||||
for (const id of ids) {
|
||||
if (fileUploads[id]) {
|
||||
delete fileUploads[id]
|
||||
}
|
||||
fileUploadStatusAtomFamily.remove(id)
|
||||
}
|
||||
set(fileUploadStatusesAtom, fileUploads)
|
||||
},
|
||||
)
|
||||
|
||||
export const clearAllFileUploadStatusesAtom = atom(
|
||||
null,
|
||||
(get, set) => {
|
||||
set(fileUploadStatusesAtom, {})
|
||||
},
|
||||
)
|
||||
|
||||
export const fileUploadCountAtom = atom(
|
||||
(get) => Object.keys(get(fileUploadStatusesAtom)).length,
|
||||
)
|
||||
|
||||
export const inProgressFileUploadCountAtom = atom((get) => {
|
||||
const statuses = get(fileUploadStatusesAtom)
|
||||
let count = 0
|
||||
for (const status in statuses) {
|
||||
if (statuses[status]?.kind === FileUploadStatusKind.InProgress) {
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
return count
|
||||
})
|
||||
|
||||
export const successfulFileUploadCountAtom = atom((get) => {
|
||||
const statuses = get(fileUploadStatusesAtom)
|
||||
let count = 0
|
||||
for (const status in statuses) {
|
||||
if (statuses[status]?.kind === FileUploadStatusKind.Success) {
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
return count
|
||||
})
|
||||
|
||||
export const hasFileUploadsErrorAtom = atom((get) => {
|
||||
const statuses = get(fileUploadStatusesAtom)
|
||||
for (const status in statuses) {
|
||||
if (statuses[status]?.kind === FileUploadStatusKind.Error) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
@@ -1,599 +0,0 @@
|
||||
import type { Doc } from "@fileone/convex/_generated/dataModel"
|
||||
import { mutationOptions } from "@tanstack/react-query"
|
||||
import { atom, useAtom, useAtomValue, useSetAtom, useStore } from "jotai"
|
||||
import { atomEffect } from "jotai-effect"
|
||||
import { atomWithMutation } from "jotai-tanstack-query"
|
||||
import {
|
||||
CircleAlertIcon,
|
||||
CircleCheckIcon,
|
||||
FilePlus2Icon,
|
||||
UploadCloudIcon,
|
||||
XIcon,
|
||||
} from "lucide-react"
|
||||
import { nanoid } from "nanoid"
|
||||
import type React from "react"
|
||||
import { useId, useMemo, useRef, useState } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Progress } from "@/components/ui/progress"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
import { formatError } from "@/lib/error"
|
||||
import {
|
||||
clearAllFileUploadStatusesAtom,
|
||||
clearFileUploadStatusesAtom,
|
||||
FileUploadStatusKind,
|
||||
fileUploadCountAtom,
|
||||
fileUploadStatusAtomFamily,
|
||||
fileUploadStatusesAtom,
|
||||
hasFileUploadsErrorAtom,
|
||||
successfulFileUploadCountAtom,
|
||||
} from "./store"
|
||||
import useUploadFile from "./use-upload-file"
|
||||
|
||||
type UploadFileDialogProps = {
|
||||
targetDirectory: Doc<"directories">
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
// Upload file atoms
|
||||
export type PickedFile = {
|
||||
id: string
|
||||
file: File
|
||||
}
|
||||
|
||||
export const pickedFilesAtom = atom<PickedFile[]>([])
|
||||
|
||||
function useUploadFilesAtom({
|
||||
targetDirectory,
|
||||
}: {
|
||||
targetDirectory: Doc<"directories">
|
||||
}) {
|
||||
const uploadFile = useUploadFile({ targetDirectory })
|
||||
const store = useStore()
|
||||
const options = useMemo(
|
||||
() =>
|
||||
mutationOptions({
|
||||
mutationFn: async (files: PickedFile[]) => {
|
||||
const promises = files.map((pickedFile) =>
|
||||
uploadFile({
|
||||
file: pickedFile.file,
|
||||
onStart: () => {
|
||||
store.set(
|
||||
fileUploadStatusAtomFamily(pickedFile.id),
|
||||
{
|
||||
kind: FileUploadStatusKind.InProgress,
|
||||
progress: 0,
|
||||
},
|
||||
)
|
||||
},
|
||||
onProgress: (progress) => {
|
||||
store.set(
|
||||
fileUploadStatusAtomFamily(pickedFile.id),
|
||||
{
|
||||
kind: FileUploadStatusKind.InProgress,
|
||||
progress,
|
||||
},
|
||||
)
|
||||
},
|
||||
}).catch((error) => {
|
||||
console.log("error", error)
|
||||
store.set(
|
||||
fileUploadStatusAtomFamily(pickedFile.id),
|
||||
{
|
||||
kind: FileUploadStatusKind.Error,
|
||||
error,
|
||||
},
|
||||
)
|
||||
throw error
|
||||
}),
|
||||
)
|
||||
return await Promise.allSettled(promises)
|
||||
},
|
||||
onSuccess: (results, files) => {
|
||||
const remainingPickedFiles: PickedFile[] = []
|
||||
results.forEach((result, i) => {
|
||||
// biome-ignore lint/style/noNonNullAssertion: results lenght must match input files array length
|
||||
const pickedFile = files[i]!
|
||||
const statusAtom = fileUploadStatusAtomFamily(
|
||||
pickedFile.id,
|
||||
)
|
||||
switch (result.status) {
|
||||
case "fulfilled":
|
||||
store.set(statusAtom, {
|
||||
kind: FileUploadStatusKind.Success,
|
||||
})
|
||||
break
|
||||
case "rejected":
|
||||
store.set(statusAtom, {
|
||||
kind: FileUploadStatusKind.Error,
|
||||
error: result.reason,
|
||||
})
|
||||
remainingPickedFiles.push(pickedFile)
|
||||
break
|
||||
}
|
||||
})
|
||||
// setPickedFiles(remainingPickedFiles)
|
||||
|
||||
if (remainingPickedFiles.length === 0) {
|
||||
toast.success("All files uploaded successfully")
|
||||
}
|
||||
},
|
||||
}),
|
||||
[uploadFile, store.set],
|
||||
)
|
||||
return useMemo(() => atomWithMutation(() => options), [options])
|
||||
}
|
||||
type UploadFilesAtom = ReturnType<typeof useUploadFilesAtom>
|
||||
|
||||
export function UploadFileDialog({
|
||||
targetDirectory,
|
||||
onClose,
|
||||
}: UploadFileDialogProps) {
|
||||
const formId = useId()
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const setPickedFiles = useSetAtom(pickedFilesAtom)
|
||||
const clearFileUploadStatuses = useSetAtom(clearFileUploadStatusesAtom)
|
||||
const store = useStore()
|
||||
|
||||
const updateFileInputEffect = useMemo(
|
||||
() =>
|
||||
atomEffect((get) => {
|
||||
const dataTransfer = new DataTransfer()
|
||||
const pickedFiles = get(pickedFilesAtom)
|
||||
for (const { file } of pickedFiles) {
|
||||
dataTransfer.items.add(file)
|
||||
}
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.files = dataTransfer.files
|
||||
}
|
||||
}),
|
||||
[],
|
||||
)
|
||||
useAtom(updateFileInputEffect)
|
||||
|
||||
const uploadFilesAtom = useUploadFilesAtom({
|
||||
targetDirectory,
|
||||
})
|
||||
|
||||
function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault()
|
||||
}
|
||||
|
||||
function openFilePicker() {
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
|
||||
function handleFileChange(event: React.ChangeEvent<HTMLInputElement>) {
|
||||
const files = event.target.files
|
||||
if (files) {
|
||||
setPickedFiles((prev) => [
|
||||
...prev,
|
||||
...Array.from(files).map((file) => ({ id: nanoid(), file })),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
function onUploadButtonClick() {
|
||||
const uploadStatuses = store.get(fileUploadStatusesAtom)
|
||||
const fileUploadCount = store.get(fileUploadCountAtom)
|
||||
const pickedFiles = store.get(pickedFilesAtom)
|
||||
const { mutate: uploadFiles, reset: restUploadFilesMutation } =
|
||||
store.get(uploadFilesAtom)
|
||||
|
||||
if (pickedFiles.length === 0) {
|
||||
// no files are picked, nothing to upload
|
||||
return
|
||||
}
|
||||
|
||||
if (fileUploadCount === 0) {
|
||||
// no files are being uploaded, upload all picked files
|
||||
uploadFiles(pickedFiles)
|
||||
return
|
||||
}
|
||||
|
||||
const successfulUploads: PickedFile["id"][] = []
|
||||
const nextPickedFiles: PickedFile[] = []
|
||||
for (const file of pickedFiles) {
|
||||
const uploadStatus = uploadStatuses[file.id]
|
||||
if (uploadStatus) {
|
||||
switch (uploadStatus.kind) {
|
||||
case FileUploadStatusKind.Success:
|
||||
successfulUploads.push(file.id)
|
||||
continue
|
||||
case FileUploadStatusKind.InProgress:
|
||||
continue
|
||||
case FileUploadStatusKind.Error:
|
||||
nextPickedFiles.push(file)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
clearFileUploadStatuses(successfulUploads)
|
||||
|
||||
if (successfulUploads.length === pickedFiles.length) {
|
||||
// all files were successfully uploaded, close the dialog
|
||||
onClose()
|
||||
} else {
|
||||
// some files were not successfully uploaded, set the next picked files
|
||||
setPickedFiles(nextPickedFiles)
|
||||
restUploadFilesMutation()
|
||||
uploadFiles(nextPickedFiles)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onClose()
|
||||
}}
|
||||
>
|
||||
<DialogContent className="sm:max-w-2xl">
|
||||
<UploadDialogHeader
|
||||
uploadFilesAtom={uploadFilesAtom}
|
||||
targetDirectory={targetDirectory}
|
||||
/>
|
||||
|
||||
<form id={formId} onSubmit={handleSubmit}>
|
||||
<input
|
||||
hidden
|
||||
multiple
|
||||
type="file"
|
||||
name="files"
|
||||
ref={fileInputRef}
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
|
||||
<UploadFileDropContainer>
|
||||
<UploadFileArea onClick={openFilePicker} />
|
||||
</UploadFileDropContainer>
|
||||
</form>
|
||||
|
||||
<DialogFooter>
|
||||
<ContinueUploadAfterSuccessfulUploadButton
|
||||
uploadFilesAtom={uploadFilesAtom}
|
||||
/>
|
||||
<SelectMoreFilesButton
|
||||
onClick={openFilePicker}
|
||||
uploadFilesAtom={uploadFilesAtom}
|
||||
/>
|
||||
<UploadButton
|
||||
uploadFilesAtom={uploadFilesAtom}
|
||||
onClick={onUploadButtonClick}
|
||||
/>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function UploadDialogHeader({
|
||||
uploadFilesAtom,
|
||||
targetDirectory,
|
||||
}: {
|
||||
uploadFilesAtom: UploadFilesAtom
|
||||
targetDirectory: Doc<"directories">
|
||||
}) {
|
||||
const { data: uploadResults, isPending: isUploading } =
|
||||
useAtomValue(uploadFilesAtom)
|
||||
const successfulUploadCount = useAtomValue(successfulFileUploadCountAtom)
|
||||
|
||||
let dialogTitle: string
|
||||
let dialogDescription: string
|
||||
if (isUploading) {
|
||||
dialogTitle = "Uploading files"
|
||||
dialogDescription =
|
||||
"You can close the dialog while they are being uploaded in the background."
|
||||
} else if (
|
||||
uploadResults &&
|
||||
uploadResults.length > 0 &&
|
||||
successfulUploadCount === uploadResults.length
|
||||
) {
|
||||
dialogTitle = "Files uploaded"
|
||||
dialogDescription =
|
||||
"Click 'Done' to close the dialog, or select more files to upload."
|
||||
} else if (targetDirectory.name) {
|
||||
dialogTitle = `Upload file to "${targetDirectory.name}"`
|
||||
dialogDescription = "Drag and drop files here or click to select files"
|
||||
} else {
|
||||
dialogTitle = "Upload file"
|
||||
dialogDescription = "Drag and drop files here or click to select files"
|
||||
}
|
||||
|
||||
return (
|
||||
<DialogHeader>
|
||||
<DialogTitle>{dialogTitle}</DialogTitle>
|
||||
<DialogDescription>{dialogDescription}</DialogDescription>
|
||||
</DialogHeader>
|
||||
)
|
||||
}
|
||||
|
||||
function ContinueUploadAfterSuccessfulUploadButton({
|
||||
uploadFilesAtom,
|
||||
}: {
|
||||
uploadFilesAtom: UploadFilesAtom
|
||||
}) {
|
||||
const setPickedFiles = useSetAtom(pickedFilesAtom)
|
||||
const clearAllFileUploadStatuses = useSetAtom(
|
||||
clearAllFileUploadStatusesAtom,
|
||||
)
|
||||
const {
|
||||
data: uploadResults,
|
||||
isPending: isUploading,
|
||||
reset: resetUploadFilesMutation,
|
||||
} = useAtomValue(uploadFilesAtom)
|
||||
const successfulUploadCount = useAtomValue(successfulFileUploadCountAtom)
|
||||
|
||||
if (
|
||||
!uploadResults ||
|
||||
uploadResults.length === 0 ||
|
||||
successfulUploadCount !== uploadResults.length
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
function resetUploadState() {
|
||||
setPickedFiles([])
|
||||
clearAllFileUploadStatuses()
|
||||
resetUploadFilesMutation()
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={resetUploadState}
|
||||
disabled={isUploading}
|
||||
>
|
||||
Upload more files
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* allows the user to select more files after they have selected some files for upload. only visible before any upload has been started.
|
||||
*/
|
||||
function SelectMoreFilesButton({
|
||||
onClick,
|
||||
uploadFilesAtom,
|
||||
}: {
|
||||
onClick: () => void
|
||||
uploadFilesAtom: UploadFilesAtom
|
||||
}) {
|
||||
const pickedFiles = useAtomValue(pickedFilesAtom)
|
||||
const { data: uploadResults, isPending: isUploading } =
|
||||
useAtomValue(uploadFilesAtom)
|
||||
|
||||
if (pickedFiles.length === 0 || uploadResults) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<Button variant="outline" onClick={onClick} disabled={isUploading}>
|
||||
Select more files
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function UploadButton({
|
||||
uploadFilesAtom,
|
||||
onClick,
|
||||
}: {
|
||||
uploadFilesAtom: UploadFilesAtom
|
||||
onClick: () => void
|
||||
}) {
|
||||
const pickedFiles = useAtomValue(pickedFilesAtom)
|
||||
const hasUploadErrors = useAtomValue(hasFileUploadsErrorAtom)
|
||||
const fileUploadCount = useAtomValue(fileUploadCountAtom)
|
||||
const { isPending: isUploading } = useAtomValue(uploadFilesAtom)
|
||||
|
||||
let label: string
|
||||
if (hasUploadErrors) {
|
||||
label = "Retry failed uploads"
|
||||
} else if (pickedFiles.length > 0) {
|
||||
if (fileUploadCount > 0) {
|
||||
label = "Done"
|
||||
} else {
|
||||
label = `Upload ${pickedFiles.length} files`
|
||||
}
|
||||
} else {
|
||||
label = "Upload"
|
||||
}
|
||||
|
||||
return (
|
||||
<Button onClick={onClick} disabled={isUploading} loading={isUploading}>
|
||||
{label}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function UploadFileDropContainer({ children }: React.PropsWithChildren) {
|
||||
const [draggedFiles, setDraggedFiles] = useState<DataTransferItem[]>([])
|
||||
const setPickedFiles = useSetAtom(pickedFilesAtom)
|
||||
|
||||
function handleDragOver(e: React.DragEvent) {
|
||||
e.preventDefault()
|
||||
const items = Array.from(e.dataTransfer.items)
|
||||
const draggedFiles = []
|
||||
for (const item of items) {
|
||||
if (item.kind === "file") {
|
||||
draggedFiles.push(item)
|
||||
}
|
||||
}
|
||||
setDraggedFiles(draggedFiles)
|
||||
}
|
||||
|
||||
function handleDragLeave() {
|
||||
setDraggedFiles([])
|
||||
}
|
||||
|
||||
function handleDrop(e: React.DragEvent) {
|
||||
e.preventDefault()
|
||||
const items = Array.from(e.dataTransfer.items)
|
||||
const droppedFiles: PickedFile[] = []
|
||||
for (const item of items) {
|
||||
const file = item.getAsFile()
|
||||
if (file) {
|
||||
droppedFiles.push({
|
||||
id: nanoid(),
|
||||
file,
|
||||
})
|
||||
}
|
||||
}
|
||||
setPickedFiles((prev) => [...prev, ...droppedFiles])
|
||||
setDraggedFiles([])
|
||||
}
|
||||
|
||||
return (
|
||||
<section
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
aria-label="File drop area"
|
||||
className="relative"
|
||||
>
|
||||
{children}
|
||||
{draggedFiles.length > 0 ? (
|
||||
<div className="border border-accent bg-primary text-primary-foreground absolute inset-0 rounded flex flex-col items-center justify-center text-sm space-y-1">
|
||||
<FilePlus2Icon className="animate-bounce" />
|
||||
<p>Drop {draggedFiles.length} files here</p>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// tag: uploadfilearea area fileuploadarea
|
||||
function UploadFileArea({ onClick }: { onClick: () => void }) {
|
||||
const [pickedFiles, setPickedFiles] = useAtom(pickedFilesAtom)
|
||||
|
||||
function removeSelectedFile(file: PickedFile) {
|
||||
setPickedFiles((prev) => prev.filter((f) => f.id !== file.id))
|
||||
}
|
||||
|
||||
if (pickedFiles.length > 0) {
|
||||
return (
|
||||
<PickedFilesList
|
||||
pickedFiles={pickedFiles}
|
||||
onRemoveFile={removeSelectedFile}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="w-full h-48 border-2 rounded border-dashed border-border flex flex-col items-center justify-center text-muted-foreground text-sm space-y-1 hover:bg-muted transition-all hover:border-solid"
|
||||
onClick={onClick}
|
||||
>
|
||||
<UploadCloudIcon />
|
||||
<span>Click to select files or drag and drop them here</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function PickedFilesList({
|
||||
pickedFiles,
|
||||
onRemoveFile,
|
||||
}: {
|
||||
pickedFiles: PickedFile[]
|
||||
onRemoveFile: (file: PickedFile) => void
|
||||
}) {
|
||||
return (
|
||||
<ul className="min-h-48 border border-border rounded bg-card text-sm">
|
||||
{pickedFiles.map((file: PickedFile) => (
|
||||
<PickedFileItem
|
||||
key={file.id}
|
||||
file={file}
|
||||
onRemove={onRemoveFile}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
function PickedFileItem({
|
||||
file: pickedFile,
|
||||
onRemove,
|
||||
}: {
|
||||
file: PickedFile
|
||||
onRemove: (file: PickedFile) => void
|
||||
}) {
|
||||
const fileUploadAtom = fileUploadStatusAtomFamily(pickedFile.id)
|
||||
const fileUpload = useAtomValue(fileUploadAtom)
|
||||
console.log("fileUpload", fileUpload)
|
||||
const { file, id } = pickedFile
|
||||
|
||||
let statusIndicator: React.ReactNode
|
||||
if (!fileUpload) {
|
||||
statusIndicator = (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => onRemove(pickedFile)}
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</Button>
|
||||
)
|
||||
} else {
|
||||
switch (fileUpload.kind) {
|
||||
case FileUploadStatusKind.InProgress:
|
||||
statusIndicator = (
|
||||
<Progress
|
||||
className="max-w-20"
|
||||
value={fileUpload.progress * 100}
|
||||
/>
|
||||
)
|
||||
break
|
||||
case FileUploadStatusKind.Error:
|
||||
statusIndicator = (
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<CircleAlertIcon className="pr-2 text-destructive" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>
|
||||
Failed to upload file:{" "}
|
||||
{formatError(fileUpload.error)}
|
||||
</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
break
|
||||
case FileUploadStatusKind.Success:
|
||||
statusIndicator = (
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<CircleCheckIcon className="pr-2 text-green-500" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>File uploaded</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<li
|
||||
className="pl-3 pr-1 py-0.5 h-8 hover:bg-muted flex justify-between items-center border-b border-border"
|
||||
key={id}
|
||||
>
|
||||
<p>{file.name} </p>
|
||||
{statusIndicator}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import type { Doc, Id } from "@fileone/convex/_generated/dataModel"
|
||||
import * as Err from "@fileone/convex/model/error"
|
||||
import {
|
||||
type DirectoryHandle,
|
||||
type FileSystemHandle,
|
||||
isSameHandle,
|
||||
} from "@fileone/convex/model/filesystem"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { useMutation as useContextMutation } from "convex/react"
|
||||
import type { PrimitiveAtom } from "jotai"
|
||||
import { useSetAtom, useStore } from "jotai"
|
||||
import { useState } from "react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
export interface FileDragInfo {
|
||||
source: FileSystemHandle
|
||||
items: FileSystemHandle[]
|
||||
}
|
||||
|
||||
export interface UseFileDropOptions {
|
||||
destItem: DirectoryHandle | null
|
||||
dragInfoAtom: PrimitiveAtom<FileDragInfo | null>
|
||||
onDropSuccess?: (
|
||||
items: Id<"files">[],
|
||||
targetDirectory: Doc<"directories">,
|
||||
) => void
|
||||
}
|
||||
|
||||
export interface UseFileDropReturn {
|
||||
isDraggedOver: boolean
|
||||
dropHandlers: {
|
||||
onDrop: (e: React.DragEvent) => void
|
||||
onDragOver: (e: React.DragEvent) => void
|
||||
onDragLeave: () => void
|
||||
}
|
||||
}
|
||||
|
||||
export function useFileDrop({
|
||||
destItem,
|
||||
dragInfoAtom,
|
||||
}: UseFileDropOptions): UseFileDropReturn {
|
||||
const [isDraggedOver, setIsDraggedOver] = useState(false)
|
||||
const setDragInfo = useSetAtom(dragInfoAtom)
|
||||
const store = useStore()
|
||||
|
||||
const { mutate: moveDroppedItems } = useMutation({
|
||||
mutationFn: useContextMutation(api.filesystem.moveItems),
|
||||
onSuccess: ({
|
||||
moved,
|
||||
errors,
|
||||
}: {
|
||||
moved: FileSystemHandle[]
|
||||
errors: Err.ApplicationErrorData[]
|
||||
}) => {
|
||||
const conflictCount = errors.reduce((acc, error) => {
|
||||
if (error.code === Err.Code.Conflict) {
|
||||
return acc + 1
|
||||
}
|
||||
return acc
|
||||
}, 0)
|
||||
if (conflictCount > 0) {
|
||||
toast.warning(
|
||||
`${moved.length} items moved${conflictCount > 0 ? `, ${conflictCount} conflicts` : ""}`,
|
||||
)
|
||||
} else {
|
||||
toast.success(`${moved.length} items moved!`)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const handleDrop = (_e: React.DragEvent) => {
|
||||
const dragInfo = store.get(dragInfoAtom)
|
||||
console.log("handleDrop", { dragInfo, destItem })
|
||||
if (dragInfo && destItem) {
|
||||
const items = dragInfo.items.filter(
|
||||
(item) => !isSameHandle(item, destItem),
|
||||
)
|
||||
if (items.length > 0) {
|
||||
moveDroppedItems({
|
||||
targetDirectory: destItem,
|
||||
items,
|
||||
})
|
||||
}
|
||||
}
|
||||
setIsDraggedOver(false)
|
||||
setDragInfo(null)
|
||||
}
|
||||
|
||||
const handleDragOver = (e: React.DragEvent) => {
|
||||
const dragInfo = store.get(dragInfoAtom)
|
||||
if (dragInfo && destItem) {
|
||||
e.preventDefault()
|
||||
e.dataTransfer.dropEffect = "move"
|
||||
setIsDraggedOver(true)
|
||||
} else {
|
||||
e.dataTransfer.dropEffect = "none"
|
||||
}
|
||||
}
|
||||
|
||||
const handleDragLeave = () => {
|
||||
setIsDraggedOver(false)
|
||||
}
|
||||
|
||||
return {
|
||||
isDraggedOver,
|
||||
dropHandlers: {
|
||||
onDrop: handleDrop,
|
||||
onDragOver: handleDragOver,
|
||||
onDragLeave: handleDragLeave,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import type { Doc, Id } from "@fileone/convex/_generated/dataModel"
|
||||
import { useMutation as useConvexMutation } from "convex/react"
|
||||
import { useCallback } from "react"
|
||||
|
||||
function useUploadFile({
|
||||
targetDirectory,
|
||||
}: {
|
||||
targetDirectory: Doc<"directories">
|
||||
}) {
|
||||
const generateUploadUrl = useConvexMutation(api.files.generateUploadUrl)
|
||||
const saveFile = useConvexMutation(api.files.saveFile)
|
||||
|
||||
async function upload({
|
||||
file,
|
||||
onStart,
|
||||
onProgress,
|
||||
}: {
|
||||
file: File
|
||||
onStart: (xhr: XMLHttpRequest) => void
|
||||
onProgress: (progress: number) => void
|
||||
}) {
|
||||
const uploadUrl = await generateUploadUrl()
|
||||
|
||||
return new Promise<{ storageId: Id<"_storage"> }>((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest()
|
||||
xhr.upload.addEventListener("progress", (e) => {
|
||||
onProgress(e.loaded / e.total)
|
||||
})
|
||||
xhr.upload.addEventListener("error", reject)
|
||||
xhr.addEventListener("load", () => {
|
||||
resolve(
|
||||
xhr.response as {
|
||||
storageId: Id<"_storage">
|
||||
},
|
||||
)
|
||||
})
|
||||
xhr.open("POST", uploadUrl)
|
||||
xhr.responseType = "json"
|
||||
xhr.setRequestHeader("Content-Type", file.type)
|
||||
xhr.send(file)
|
||||
onStart(xhr)
|
||||
}).then(({ storageId }) =>
|
||||
saveFile({
|
||||
storageId,
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
mimeType: file.type,
|
||||
directoryId: targetDirectory._id,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
return useCallback(upload, [])
|
||||
}
|
||||
|
||||
export default useUploadFile
|
||||
@@ -1,21 +0,0 @@
|
||||
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,12 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Bun + React</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="./entry.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,37 +0,0 @@
|
||||
import {
|
||||
Code as ErrorCode,
|
||||
isApplicationError,
|
||||
} from "@fileone/convex/model/error"
|
||||
import { toast } from "sonner"
|
||||
|
||||
const ERROR_MESSAGE = {
|
||||
[ErrorCode.DirectoryExists]: "Directory already exists",
|
||||
[ErrorCode.FileExists]: "File already exists",
|
||||
[ErrorCode.Internal]: "Internal application error",
|
||||
[ErrorCode.Conflict]: "Conflict",
|
||||
[ErrorCode.DirectoryNotFound]: "Directory not found",
|
||||
[ErrorCode.FileNotFound]: "File not found",
|
||||
[ErrorCode.Unauthenticated]: "Unauthenticated",
|
||||
} as const
|
||||
|
||||
export function formatError(error: unknown): string {
|
||||
if (isApplicationError(error)) {
|
||||
return ERROR_MESSAGE[error.data.code]
|
||||
}
|
||||
if (error instanceof Error) {
|
||||
return error.message
|
||||
}
|
||||
return "Unknown error"
|
||||
}
|
||||
|
||||
export function defaultOnError(error: unknown) {
|
||||
console.log(error)
|
||||
toast.error(formatError(error))
|
||||
}
|
||||
|
||||
export function withDefaultOnError(fn: (error: unknown) => void) {
|
||||
return (error: unknown) => {
|
||||
defaultOnError(error)
|
||||
fn(error)
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
import { atom, useSetAtom } from "jotai"
|
||||
import { useEffect } from "react"
|
||||
|
||||
export enum KeyboardModifier {
|
||||
Alt = "Alt",
|
||||
Control = "Control",
|
||||
Meta = "Meta",
|
||||
Shift = "Shift",
|
||||
}
|
||||
|
||||
export const keyboardModifierAtom = atom(new Set<KeyboardModifier>())
|
||||
|
||||
const addKeyboardModifierAtom = atom(
|
||||
null,
|
||||
(get, set, modifier: KeyboardModifier) => {
|
||||
const activeModifiers = get(keyboardModifierAtom)
|
||||
const nextActiveModifiers = new Set(activeModifiers)
|
||||
nextActiveModifiers.add(modifier)
|
||||
set(keyboardModifierAtom, nextActiveModifiers)
|
||||
},
|
||||
)
|
||||
const removeKeyboardModifierAtom = atom(
|
||||
null,
|
||||
(get, set, modifier: KeyboardModifier) => {
|
||||
const activeModifiers = get(keyboardModifierAtom)
|
||||
const nextActiveModifiers = new Set(activeModifiers)
|
||||
nextActiveModifiers.delete(modifier)
|
||||
set(keyboardModifierAtom, nextActiveModifiers)
|
||||
},
|
||||
)
|
||||
|
||||
export function useKeyboardModifierListener() {
|
||||
const addKeyboardModifier = useSetAtom(addKeyboardModifierAtom)
|
||||
const removeKeyboardModifier = useSetAtom(removeKeyboardModifierAtom)
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
switch (event.key) {
|
||||
case "Alt":
|
||||
addKeyboardModifier(KeyboardModifier.Alt)
|
||||
break
|
||||
case "Control":
|
||||
addKeyboardModifier(KeyboardModifier.Control)
|
||||
break
|
||||
case "Meta":
|
||||
addKeyboardModifier(KeyboardModifier.Meta)
|
||||
break
|
||||
case "Shift":
|
||||
addKeyboardModifier(KeyboardModifier.Shift)
|
||||
break
|
||||
}
|
||||
}
|
||||
const handleKeyUp = (event: KeyboardEvent) => {
|
||||
switch (event.key) {
|
||||
case "Alt":
|
||||
removeKeyboardModifier(KeyboardModifier.Alt)
|
||||
break
|
||||
case "Control":
|
||||
removeKeyboardModifier(KeyboardModifier.Control)
|
||||
break
|
||||
case "Meta":
|
||||
removeKeyboardModifier(KeyboardModifier.Meta)
|
||||
break
|
||||
case "Shift":
|
||||
removeKeyboardModifier(KeyboardModifier.Shift)
|
||||
break
|
||||
}
|
||||
}
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
window.addEventListener("keyup", handleKeyUp)
|
||||
return () => {
|
||||
window.removeEventListener("keydown", handleKeyDown)
|
||||
window.removeEventListener("keyup", handleKeyUp)
|
||||
}
|
||||
}, [addKeyboardModifier, removeKeyboardModifier])
|
||||
}
|
||||
|
||||
export function isControlOrCommandKeyActive(
|
||||
keyboardModifiers: Set<KeyboardModifier>,
|
||||
) {
|
||||
return (
|
||||
keyboardModifiers.has(KeyboardModifier.Control) ||
|
||||
keyboardModifiers.has(KeyboardModifier.Meta)
|
||||
)
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import { type ClassValue, clsx } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
/* eslint-disable */
|
||||
|
||||
// @ts-nocheck
|
||||
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
|
||||
// This file was automatically generated by TanStack Router.
|
||||
// You should NOT make any changes in this file as it will be overwritten.
|
||||
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
|
||||
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as SignUpRouteImport } from './routes/sign-up'
|
||||
import { Route as LoginRouteImport } from './routes/login'
|
||||
import { Route as AuthenticatedRouteImport } from './routes/_authenticated'
|
||||
import { Route as AuthenticatedIndexRouteImport } from './routes/_authenticated/index'
|
||||
import { Route as LoginCallbackRouteImport } from './routes/login_.callback'
|
||||
import { Route as AuthenticatedSidebarLayoutRouteImport } from './routes/_authenticated/_sidebar-layout'
|
||||
import { Route as AuthenticatedSidebarLayoutHomeRouteImport } from './routes/_authenticated/_sidebar-layout/home'
|
||||
import { Route as AuthenticatedSidebarLayoutDirectoriesDirectoryIdRouteImport } from './routes/_authenticated/_sidebar-layout/directories.$directoryId'
|
||||
import { Route as AuthenticatedSidebarLayoutTrashDirectoriesDirectoryIdRouteImport } from './routes/_authenticated/_sidebar-layout/trash.directories.$directoryId'
|
||||
|
||||
const SignUpRoute = SignUpRouteImport.update({
|
||||
id: '/sign-up',
|
||||
path: '/sign-up',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const LoginRoute = LoginRouteImport.update({
|
||||
id: '/login',
|
||||
path: '/login',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const AuthenticatedRoute = AuthenticatedRouteImport.update({
|
||||
id: '/_authenticated',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const AuthenticatedIndexRoute = AuthenticatedIndexRouteImport.update({
|
||||
id: '/',
|
||||
path: '/',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const LoginCallbackRoute = LoginCallbackRouteImport.update({
|
||||
id: '/login_/callback',
|
||||
path: '/login/callback',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const AuthenticatedSidebarLayoutRoute =
|
||||
AuthenticatedSidebarLayoutRouteImport.update({
|
||||
id: '/_sidebar-layout',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedSidebarLayoutHomeRoute =
|
||||
AuthenticatedSidebarLayoutHomeRouteImport.update({
|
||||
id: '/home',
|
||||
path: '/home',
|
||||
getParentRoute: () => AuthenticatedSidebarLayoutRoute,
|
||||
} as any)
|
||||
const AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute =
|
||||
AuthenticatedSidebarLayoutDirectoriesDirectoryIdRouteImport.update({
|
||||
id: '/directories/$directoryId',
|
||||
path: '/directories/$directoryId',
|
||||
getParentRoute: () => AuthenticatedSidebarLayoutRoute,
|
||||
} as any)
|
||||
const AuthenticatedSidebarLayoutTrashDirectoriesDirectoryIdRoute =
|
||||
AuthenticatedSidebarLayoutTrashDirectoriesDirectoryIdRouteImport.update({
|
||||
id: '/trash/directories/$directoryId',
|
||||
path: '/trash/directories/$directoryId',
|
||||
getParentRoute: () => AuthenticatedSidebarLayoutRoute,
|
||||
} as any)
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/login': typeof LoginRoute
|
||||
'/sign-up': typeof SignUpRoute
|
||||
'/login/callback': typeof LoginCallbackRoute
|
||||
'/': typeof AuthenticatedIndexRoute
|
||||
'/home': typeof AuthenticatedSidebarLayoutHomeRoute
|
||||
'/directories/$directoryId': typeof AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute
|
||||
'/trash/directories/$directoryId': typeof AuthenticatedSidebarLayoutTrashDirectoriesDirectoryIdRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/login': typeof LoginRoute
|
||||
'/sign-up': typeof SignUpRoute
|
||||
'/login/callback': typeof LoginCallbackRoute
|
||||
'/': typeof AuthenticatedIndexRoute
|
||||
'/home': typeof AuthenticatedSidebarLayoutHomeRoute
|
||||
'/directories/$directoryId': typeof AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute
|
||||
'/trash/directories/$directoryId': typeof AuthenticatedSidebarLayoutTrashDirectoriesDirectoryIdRoute
|
||||
}
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/_authenticated': typeof AuthenticatedRouteWithChildren
|
||||
'/login': typeof LoginRoute
|
||||
'/sign-up': typeof SignUpRoute
|
||||
'/_authenticated/_sidebar-layout': typeof AuthenticatedSidebarLayoutRouteWithChildren
|
||||
'/login_/callback': typeof LoginCallbackRoute
|
||||
'/_authenticated/': typeof AuthenticatedIndexRoute
|
||||
'/_authenticated/_sidebar-layout/home': typeof AuthenticatedSidebarLayoutHomeRoute
|
||||
'/_authenticated/_sidebar-layout/directories/$directoryId': typeof AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute
|
||||
'/_authenticated/_sidebar-layout/trash/directories/$directoryId': typeof AuthenticatedSidebarLayoutTrashDirectoriesDirectoryIdRoute
|
||||
}
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths:
|
||||
| '/login'
|
||||
| '/sign-up'
|
||||
| '/login/callback'
|
||||
| '/'
|
||||
| '/home'
|
||||
| '/directories/$directoryId'
|
||||
| '/trash/directories/$directoryId'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to:
|
||||
| '/login'
|
||||
| '/sign-up'
|
||||
| '/login/callback'
|
||||
| '/'
|
||||
| '/home'
|
||||
| '/directories/$directoryId'
|
||||
| '/trash/directories/$directoryId'
|
||||
id:
|
||||
| '__root__'
|
||||
| '/_authenticated'
|
||||
| '/login'
|
||||
| '/sign-up'
|
||||
| '/_authenticated/_sidebar-layout'
|
||||
| '/login_/callback'
|
||||
| '/_authenticated/'
|
||||
| '/_authenticated/_sidebar-layout/home'
|
||||
| '/_authenticated/_sidebar-layout/directories/$directoryId'
|
||||
| '/_authenticated/_sidebar-layout/trash/directories/$directoryId'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
AuthenticatedRoute: typeof AuthenticatedRouteWithChildren
|
||||
LoginRoute: typeof LoginRoute
|
||||
SignUpRoute: typeof SignUpRoute
|
||||
LoginCallbackRoute: typeof LoginCallbackRoute
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface FileRoutesByPath {
|
||||
'/sign-up': {
|
||||
id: '/sign-up'
|
||||
path: '/sign-up'
|
||||
fullPath: '/sign-up'
|
||||
preLoaderRoute: typeof SignUpRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/login': {
|
||||
id: '/login'
|
||||
path: '/login'
|
||||
fullPath: '/login'
|
||||
preLoaderRoute: typeof LoginRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/_authenticated': {
|
||||
id: '/_authenticated'
|
||||
path: ''
|
||||
fullPath: ''
|
||||
preLoaderRoute: typeof AuthenticatedRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/_authenticated/': {
|
||||
id: '/_authenticated/'
|
||||
path: '/'
|
||||
fullPath: '/'
|
||||
preLoaderRoute: typeof AuthenticatedIndexRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/login_/callback': {
|
||||
id: '/login_/callback'
|
||||
path: '/login/callback'
|
||||
fullPath: '/login/callback'
|
||||
preLoaderRoute: typeof LoginCallbackRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/_authenticated/_sidebar-layout': {
|
||||
id: '/_authenticated/_sidebar-layout'
|
||||
path: ''
|
||||
fullPath: ''
|
||||
preLoaderRoute: typeof AuthenticatedSidebarLayoutRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/_sidebar-layout/home': {
|
||||
id: '/_authenticated/_sidebar-layout/home'
|
||||
path: '/home'
|
||||
fullPath: '/home'
|
||||
preLoaderRoute: typeof AuthenticatedSidebarLayoutHomeRouteImport
|
||||
parentRoute: typeof AuthenticatedSidebarLayoutRoute
|
||||
}
|
||||
'/_authenticated/_sidebar-layout/directories/$directoryId': {
|
||||
id: '/_authenticated/_sidebar-layout/directories/$directoryId'
|
||||
path: '/directories/$directoryId'
|
||||
fullPath: '/directories/$directoryId'
|
||||
preLoaderRoute: typeof AuthenticatedSidebarLayoutDirectoriesDirectoryIdRouteImport
|
||||
parentRoute: typeof AuthenticatedSidebarLayoutRoute
|
||||
}
|
||||
'/_authenticated/_sidebar-layout/trash/directories/$directoryId': {
|
||||
id: '/_authenticated/_sidebar-layout/trash/directories/$directoryId'
|
||||
path: '/trash/directories/$directoryId'
|
||||
fullPath: '/trash/directories/$directoryId'
|
||||
preLoaderRoute: typeof AuthenticatedSidebarLayoutTrashDirectoriesDirectoryIdRouteImport
|
||||
parentRoute: typeof AuthenticatedSidebarLayoutRoute
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface AuthenticatedSidebarLayoutRouteChildren {
|
||||
AuthenticatedSidebarLayoutHomeRoute: typeof AuthenticatedSidebarLayoutHomeRoute
|
||||
AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute: typeof AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute
|
||||
AuthenticatedSidebarLayoutTrashDirectoriesDirectoryIdRoute: typeof AuthenticatedSidebarLayoutTrashDirectoriesDirectoryIdRoute
|
||||
}
|
||||
|
||||
const AuthenticatedSidebarLayoutRouteChildren: AuthenticatedSidebarLayoutRouteChildren =
|
||||
{
|
||||
AuthenticatedSidebarLayoutHomeRoute: AuthenticatedSidebarLayoutHomeRoute,
|
||||
AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute:
|
||||
AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute,
|
||||
AuthenticatedSidebarLayoutTrashDirectoriesDirectoryIdRoute:
|
||||
AuthenticatedSidebarLayoutTrashDirectoriesDirectoryIdRoute,
|
||||
}
|
||||
|
||||
const AuthenticatedSidebarLayoutRouteWithChildren =
|
||||
AuthenticatedSidebarLayoutRoute._addFileChildren(
|
||||
AuthenticatedSidebarLayoutRouteChildren,
|
||||
)
|
||||
|
||||
interface AuthenticatedRouteChildren {
|
||||
AuthenticatedSidebarLayoutRoute: typeof AuthenticatedSidebarLayoutRouteWithChildren
|
||||
AuthenticatedIndexRoute: typeof AuthenticatedIndexRoute
|
||||
}
|
||||
|
||||
const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
|
||||
AuthenticatedSidebarLayoutRoute: AuthenticatedSidebarLayoutRouteWithChildren,
|
||||
AuthenticatedIndexRoute: AuthenticatedIndexRoute,
|
||||
}
|
||||
|
||||
const AuthenticatedRouteWithChildren = AuthenticatedRoute._addFileChildren(
|
||||
AuthenticatedRouteChildren,
|
||||
)
|
||||
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
AuthenticatedRoute: AuthenticatedRouteWithChildren,
|
||||
LoginRoute: LoginRoute,
|
||||
SignUpRoute: SignUpRoute,
|
||||
LoginCallbackRoute: LoginCallbackRoute,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
._addFileChildren(rootRouteChildren)
|
||||
._addFileTypes<FileRouteTypes>()
|
||||
@@ -1,45 +0,0 @@
|
||||
import "@/styles/globals.css"
|
||||
import { ConvexBetterAuthProvider } from "@convex-dev/better-auth/react"
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
|
||||
import { createRootRoute, Outlet } from "@tanstack/react-router"
|
||||
import { ConvexReactClient } from "convex/react"
|
||||
import { toast } from "sonner"
|
||||
import { Toaster } from "@/components/ui/sonner"
|
||||
import { formatError } from "@/lib/error"
|
||||
import { useKeyboardModifierListener } from "@/lib/keyboard"
|
||||
import { authClient } from "../auth"
|
||||
|
||||
export const Route = createRootRoute({
|
||||
component: RootLayout,
|
||||
})
|
||||
|
||||
const convexClient = new ConvexReactClient(process.env.BUN_PUBLIC_CONVEX_URL!, {
|
||||
verbose: true,
|
||||
})
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
mutations: {
|
||||
onError: (error) => {
|
||||
console.log(error)
|
||||
toast.error(formatError(error))
|
||||
},
|
||||
throwOnError: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
function RootLayout() {
|
||||
useKeyboardModifierListener()
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ConvexBetterAuthProvider
|
||||
client={convexClient}
|
||||
authClient={authClient}
|
||||
>
|
||||
<Outlet />
|
||||
<Toaster />
|
||||
</ConvexBetterAuthProvider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
import {
|
||||
createFileRoute,
|
||||
Navigate,
|
||||
Outlet,
|
||||
useLocation,
|
||||
} from "@tanstack/react-router"
|
||||
import {
|
||||
Authenticated,
|
||||
AuthLoading,
|
||||
Unauthenticated,
|
||||
useConvexAuth,
|
||||
} from "convex/react"
|
||||
import { useEffect, useState } from "react"
|
||||
import { authClient, SessionContext } from "@/auth"
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner"
|
||||
|
||||
export const Route = createFileRoute("/_authenticated")({
|
||||
component: AuthenticatedLayout,
|
||||
})
|
||||
|
||||
function AuthenticatedLayout() {
|
||||
const { search } = useLocation()
|
||||
const { isLoading, isAuthenticated } = useConvexAuth()
|
||||
const { data: session, isPending: sessionLoading } = authClient.useSession()
|
||||
const [hasProcessedAuth, setHasProcessedAuth] = useState(false)
|
||||
|
||||
// Check if we're in the middle of processing an auth code
|
||||
const hasAuthCode = search && typeof search === "object" && "code" in search
|
||||
|
||||
// Track when auth processing is complete
|
||||
useEffect(() => {
|
||||
if (!sessionLoading && !isLoading) {
|
||||
// Delay to ensure auth state is fully synchronized
|
||||
const timer = setTimeout(() => {
|
||||
setHasProcessedAuth(true)
|
||||
}, 0)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [sessionLoading, isLoading])
|
||||
|
||||
// Show loading during auth code processing or while auth state is syncing
|
||||
if (hasAuthCode || sessionLoading || isLoading || !hasProcessedAuth) {
|
||||
return (
|
||||
<div className="flex h-screen w-full items-center justify-center">
|
||||
<LoadingSpinner className="size-10" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Authenticated>
|
||||
{session ? (
|
||||
<SessionContext value={session}>
|
||||
<Outlet />
|
||||
</SessionContext>
|
||||
) : (
|
||||
<Outlet />
|
||||
)}
|
||||
</Authenticated>
|
||||
<Unauthenticated>
|
||||
{/* <Navigate replace to="/login" /> */}
|
||||
</Unauthenticated>
|
||||
<AuthLoading>
|
||||
<div className="flex h-screen w-full items-center justify-center">
|
||||
<LoadingSpinner className="size-10" />
|
||||
</div>
|
||||
</AuthLoading>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import { createFileRoute, Outlet } from "@tanstack/react-router"
|
||||
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
|
||||
import { Toaster } from "@/components/ui/sonner"
|
||||
import { DashboardSidebar } from "@/dashboard/dashboard-sidebar"
|
||||
|
||||
export const Route = createFileRoute("/_authenticated/_sidebar-layout")({
|
||||
component: RouteComponent,
|
||||
})
|
||||
|
||||
function RouteComponent() {
|
||||
return (
|
||||
<SidebarProvider>
|
||||
<div className="flex h-screen w-full">
|
||||
<DashboardSidebar />
|
||||
<SidebarInset>
|
||||
<Outlet />
|
||||
</SidebarInset>
|
||||
</div>
|
||||
</SidebarProvider>
|
||||
)
|
||||
}
|
||||
@@ -1,400 +0,0 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import type { Doc, Id } from "@fileone/convex/_generated/dataModel"
|
||||
import {
|
||||
type FileSystemItem,
|
||||
FileType,
|
||||
newFileSystemHandle,
|
||||
} from "@fileone/convex/model/filesystem"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
import type { Row, Table } from "@tanstack/react-table"
|
||||
import {
|
||||
useMutation as useContextMutation,
|
||||
useQuery as useConvexQuery,
|
||||
} from "convex/react"
|
||||
import { atom, useAtom, useAtomValue, useSetAtom, useStore } from "jotai"
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
PlusIcon,
|
||||
TextCursorInputIcon,
|
||||
TrashIcon,
|
||||
} from "lucide-react"
|
||||
import { useCallback, useContext } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { DirectoryIcon } from "@/components/icons/directory-icon"
|
||||
import { TextFileIcon } from "@/components/icons/text-file-icon"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuTrigger,
|
||||
} from "@/components/ui/context-menu"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { WithAtom } from "@/components/with-atom"
|
||||
import { DirectoryPageContext } from "@/directories/directory-page/context"
|
||||
import { DirectoryContentTable } from "@/directories/directory-page/directory-content-table"
|
||||
import { DirectoryPageSkeleton } from "@/directories/directory-page/directory-page-skeleton"
|
||||
import { FilePathBreadcrumb } from "@/directories/directory-page/file-path-breadcrumb"
|
||||
import { NewDirectoryDialog } from "@/directories/directory-page/new-directory-dialog"
|
||||
import { RenameFileDialog } from "@/directories/directory-page/rename-file-dialog"
|
||||
import { FilePreviewDialog } from "@/files/file-preview-dialog"
|
||||
import { inProgressFileUploadCountAtom } from "@/files/store"
|
||||
import { UploadFileDialog } from "@/files/upload-file-dialog"
|
||||
import type { FileDragInfo } from "@/files/use-file-drop"
|
||||
|
||||
export const Route = createFileRoute(
|
||||
"/_authenticated/_sidebar-layout/directories/$directoryId",
|
||||
)({
|
||||
component: RouteComponent,
|
||||
})
|
||||
|
||||
enum DialogKind {
|
||||
NewDirectory = "NewDirectory",
|
||||
UploadFile = "UploadFile",
|
||||
}
|
||||
|
||||
type NewDirectoryDialogData = {
|
||||
kind: DialogKind.NewDirectory
|
||||
}
|
||||
|
||||
type UploadFileDialogData = {
|
||||
kind: DialogKind.UploadFile
|
||||
directory: Doc<"directories">
|
||||
}
|
||||
|
||||
type ActiveDialogData = NewDirectoryDialogData | UploadFileDialogData
|
||||
|
||||
// MARK: atoms
|
||||
const contextMenuTargetItemsAtom = atom<FileSystemItem[]>([])
|
||||
const activeDialogDataAtom = atom<ActiveDialogData | null>(null)
|
||||
const fileDragInfoAtom = atom<FileDragInfo | null>(null)
|
||||
const optimisticDeletedItemsAtom = atom(
|
||||
new Set<Id<"files"> | Id<"directories">>(),
|
||||
)
|
||||
const openedFileAtom = atom<Doc<"files"> | null>(null)
|
||||
const itemBeingRenamedAtom = atom<{
|
||||
originalItem: FileSystemItem
|
||||
name: string
|
||||
} | null>(null)
|
||||
|
||||
// MARK: page entry
|
||||
function RouteComponent() {
|
||||
const { directoryId } = Route.useParams()
|
||||
const rootDirectory = useConvexQuery(api.files.fetchRootDirectory)
|
||||
const directory = useConvexQuery(api.files.fetchDirectory, {
|
||||
directoryId,
|
||||
})
|
||||
const store = useStore()
|
||||
const directoryContent = useConvexQuery(
|
||||
api.filesystem.fetchDirectoryContent,
|
||||
{
|
||||
directoryId,
|
||||
trashed: false,
|
||||
},
|
||||
)
|
||||
const setOpenedFile = useSetAtom(openedFileAtom)
|
||||
const setContextMenuTargetItems = useSetAtom(contextMenuTargetItemsAtom)
|
||||
|
||||
const tableFilter = useCallback(
|
||||
(item: FileSystemItem) =>
|
||||
store.get(optimisticDeletedItemsAtom).has(item.doc._id),
|
||||
[store],
|
||||
)
|
||||
|
||||
const openFile = useCallback(
|
||||
(file: Doc<"files">) => {
|
||||
setOpenedFile(file)
|
||||
},
|
||||
[setOpenedFile],
|
||||
)
|
||||
|
||||
const directoryUrlFn = useCallback(
|
||||
(directory: Doc<"directories">) => `/directories/${directory._id}`,
|
||||
[],
|
||||
)
|
||||
|
||||
const directoryUrlById = useCallback(
|
||||
(directoryId: Id<"directories">) => `/directories/${directoryId}`,
|
||||
[],
|
||||
)
|
||||
|
||||
const handleContextMenuRequest = (
|
||||
row: Row<FileSystemItem>,
|
||||
table: Table<FileSystemItem>,
|
||||
) => {
|
||||
if (row.getIsSelected()) {
|
||||
setContextMenuTargetItems(
|
||||
table.getSelectedRowModel().rows.map((row) => row.original),
|
||||
)
|
||||
} else {
|
||||
setContextMenuTargetItems([row.original])
|
||||
}
|
||||
}
|
||||
|
||||
if (!directory || !directoryContent || !rootDirectory) {
|
||||
return <DirectoryPageSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<DirectoryPageContext
|
||||
value={{ rootDirectory, directory, directoryContent }}
|
||||
>
|
||||
<header className="flex py-2 shrink-0 items-center gap-2 border-b px-4 w-full">
|
||||
<FilePathBreadcrumb
|
||||
rootLabel="All Files"
|
||||
directoryUrlFn={directoryUrlById}
|
||||
/>
|
||||
<div className="ml-auto flex flex-row gap-2">
|
||||
<NewDirectoryItemDropdown />
|
||||
<UploadFileButton />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* DirectoryContentContextMenu must wrap div instead of DirectoryContentTable, otherwise radix will throw "event.preventDefault is not a function" error, idk why */}
|
||||
<DirectoryContentContextMenu>
|
||||
<div className="w-full">
|
||||
<DirectoryContentTable
|
||||
filterFn={tableFilter}
|
||||
directoryUrlFn={directoryUrlFn}
|
||||
fileDragInfoAtom={fileDragInfoAtom}
|
||||
onContextMenu={handleContextMenuRequest}
|
||||
onOpenFile={openFile}
|
||||
/>
|
||||
</div>
|
||||
</DirectoryContentContextMenu>
|
||||
|
||||
<WithAtom atom={activeDialogDataAtom}>
|
||||
{(data, setData) => (
|
||||
<>
|
||||
<NewDirectoryDialog
|
||||
open={data?.kind === DialogKind.NewDirectory}
|
||||
directoryId={directory._id}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setData(null)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{data?.kind === DialogKind.UploadFile && (
|
||||
<UploadFileDialog
|
||||
targetDirectory={data.directory}
|
||||
onClose={() => setData(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</WithAtom>
|
||||
|
||||
<WithAtom atom={itemBeingRenamedAtom}>
|
||||
{(itemBeingRenamed, setItemBeingRenamed) => {
|
||||
if (!itemBeingRenamed) return null
|
||||
return (
|
||||
<RenameFileDialog
|
||||
item={itemBeingRenamed.originalItem}
|
||||
onRenameSuccess={() => {
|
||||
toast.success("File renamed successfully")
|
||||
setItemBeingRenamed(null)
|
||||
}}
|
||||
onClose={() => setItemBeingRenamed(null)}
|
||||
/>
|
||||
)
|
||||
}}
|
||||
</WithAtom>
|
||||
|
||||
<WithAtom atom={openedFileAtom}>
|
||||
{(openedFile, setOpenedFile) => {
|
||||
if (!openedFile) return null
|
||||
return (
|
||||
<FilePreviewDialog
|
||||
file={openedFile}
|
||||
onClose={() => setOpenedFile(null)}
|
||||
/>
|
||||
)
|
||||
}}
|
||||
</WithAtom>
|
||||
</DirectoryPageContext>
|
||||
)
|
||||
}
|
||||
|
||||
// ==================================
|
||||
// MARK: DirectoryContentContextMenu
|
||||
|
||||
function DirectoryContentContextMenu({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const store = useStore()
|
||||
const [target, setTarget] = useAtom(contextMenuTargetItemsAtom)
|
||||
const setOptimisticDeletedItems = useSetAtom(optimisticDeletedItemsAtom)
|
||||
const moveToTrashMutation = useContextMutation(api.filesystem.moveToTrash)
|
||||
|
||||
const { mutate: moveToTrash } = useMutation({
|
||||
mutationFn: moveToTrashMutation,
|
||||
onMutate: ({ handles }) => {
|
||||
setOptimisticDeletedItems(
|
||||
(prev) =>
|
||||
new Set([...prev, ...handles.map((handle) => handle.id)]),
|
||||
)
|
||||
},
|
||||
onSuccess: ({ deleted, errors }, { handles }) => {
|
||||
setOptimisticDeletedItems((prev) => {
|
||||
const newSet = new Set(prev)
|
||||
for (const handle of handles) {
|
||||
newSet.delete(handle.id)
|
||||
}
|
||||
return newSet
|
||||
})
|
||||
if (errors.length === 0 && deleted.length === handles.length) {
|
||||
toast.success(`Moved ${handles.length} items to trash`)
|
||||
} else if (errors.length === handles.length) {
|
||||
toast.error("Failed to move to trash")
|
||||
} else {
|
||||
toast.info(
|
||||
`Moved ${deleted.length} items to trash; failed to move ${errors.length} items`,
|
||||
)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const handleDelete = () => {
|
||||
const selectedItems = store.get(contextMenuTargetItemsAtom)
|
||||
if (selectedItems.length > 0) {
|
||||
moveToTrash({
|
||||
handles: selectedItems.map(newFileSystemHandle),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ContextMenu
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setTarget([])
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
|
||||
{target.length > 0 && (
|
||||
<ContextMenuContent>
|
||||
<RenameMenuItem />
|
||||
<ContextMenuItem
|
||||
variant="destructive"
|
||||
onClick={handleDelete}
|
||||
>
|
||||
<TrashIcon />
|
||||
Move to trash
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
)}
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
|
||||
function RenameMenuItem() {
|
||||
const store = useStore()
|
||||
const target = useAtomValue(contextMenuTargetItemsAtom)
|
||||
const setItemBeingRenamed = useSetAtom(itemBeingRenamedAtom)
|
||||
|
||||
const handleRename = () => {
|
||||
const selectedItems = store.get(contextMenuTargetItemsAtom)
|
||||
if (selectedItems.length === 1) {
|
||||
// biome-ignore lint/style/noNonNullAssertion: length is checked
|
||||
const selectedItem = selectedItems[0]!
|
||||
setItemBeingRenamed({
|
||||
originalItem: selectedItem,
|
||||
name: selectedItem.doc.name,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Only render if exactly one item is selected
|
||||
if (target.length !== 1) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<ContextMenuItem onClick={handleRename}>
|
||||
<TextCursorInputIcon />
|
||||
Rename
|
||||
</ContextMenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
// ==================================
|
||||
|
||||
// tags: upload, uploadfile, uploadfilebutton, fileupload, fileuploadbutton
|
||||
function UploadFileButton() {
|
||||
const { directory } = useContext(DirectoryPageContext)
|
||||
const setActiveDialogData = useSetAtom(activeDialogDataAtom)
|
||||
const inProgressFileUploadCount = useAtomValue(
|
||||
inProgressFileUploadCountAtom,
|
||||
)
|
||||
|
||||
const handleClick = () => {
|
||||
setActiveDialogData({
|
||||
kind: DialogKind.UploadFile,
|
||||
directory: directory,
|
||||
})
|
||||
}
|
||||
|
||||
if (inProgressFileUploadCount > 0) {
|
||||
return (
|
||||
<Button size="sm" type="button" loading onClick={handleClick}>
|
||||
Uploading {inProgressFileUploadCount} files
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Button size="sm" type="button" onClick={handleClick}>
|
||||
Upload files
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function NewDirectoryItemDropdown() {
|
||||
const [activeDialogData, setActiveDialogData] =
|
||||
useAtom(activeDialogDataAtom)
|
||||
|
||||
const addNewDirectory = () => {
|
||||
setActiveDialogData({
|
||||
kind: DialogKind.NewDirectory,
|
||||
})
|
||||
}
|
||||
|
||||
const handleCloseAutoFocus = (event: Event) => {
|
||||
// If we just created a new item, prevent the dropdown from restoring focus to the trigger
|
||||
if (activeDialogData) {
|
||||
event.preventDefault()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button size="sm" type="button" variant="outline">
|
||||
<PlusIcon className="size-4" />
|
||||
New
|
||||
<ChevronDownIcon className="pl-1 size-4 shrink-0" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent onCloseAutoFocus={handleCloseAutoFocus}>
|
||||
<DropdownMenuItem>
|
||||
<TextFileIcon />
|
||||
Text file
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={addNewDirectory}>
|
||||
<DirectoryIcon />
|
||||
Directory
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
|
||||
export const Route = createFileRoute("/_authenticated/_sidebar-layout/home")({
|
||||
component: RouteComponent,
|
||||
})
|
||||
|
||||
function RouteComponent() {
|
||||
return <div>Hello "/_authenticated/home"!</div>
|
||||
}
|
||||
@@ -1,402 +0,0 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import type { Doc, Id } from "@fileone/convex/_generated/dataModel"
|
||||
import {
|
||||
type FileSystemItem,
|
||||
FileType,
|
||||
newFileSystemHandle,
|
||||
} from "@fileone/convex/model/filesystem"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
import type { Row, Table } from "@tanstack/react-table"
|
||||
import {
|
||||
useMutation as useConvexMutation,
|
||||
useQuery as useConvexQuery,
|
||||
} from "convex/react"
|
||||
import { atom, useAtom, useSetAtom, useStore } from "jotai"
|
||||
import { ShredderIcon, TrashIcon, UndoIcon } from "lucide-react"
|
||||
import { useCallback, useContext, useEffect } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuTrigger,
|
||||
} from "@/components/ui/context-menu"
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { WithAtom } from "@/components/with-atom"
|
||||
import { DirectoryPageContext } from "@/directories/directory-page/context"
|
||||
import { DirectoryContentTable } from "@/directories/directory-page/directory-content-table"
|
||||
import { DirectoryPageSkeleton } from "@/directories/directory-page/directory-page-skeleton"
|
||||
import { FilePathBreadcrumb } from "@/directories/directory-page/file-path-breadcrumb"
|
||||
import { FilePreviewDialog } from "@/files/file-preview-dialog"
|
||||
import type { FileDragInfo } from "@/files/use-file-drop"
|
||||
import { backgroundTaskProgressAtom } from "../../../dashboard/state"
|
||||
|
||||
export const Route = createFileRoute(
|
||||
"/_authenticated/_sidebar-layout/trash/directories/$directoryId",
|
||||
)({
|
||||
component: RouteComponent,
|
||||
})
|
||||
|
||||
enum ActiveDialogKind {
|
||||
DeleteConfirmation = "DeleteConfirmation",
|
||||
EmptyTrashConfirmation = "EmptyTrashConfirmation",
|
||||
}
|
||||
|
||||
const contextMenuTargetItemsAtom = atom<FileSystemItem[]>([])
|
||||
const fileDragInfoAtom = atom<FileDragInfo | null>(null)
|
||||
const activeDialogAtom = atom<ActiveDialogKind | null>(null)
|
||||
const openedFileAtom = atom<Doc<"files"> | null>(null)
|
||||
const optimisticRemovedItemsAtom = atom(
|
||||
new Set<Id<"files"> | Id<"directories">>(),
|
||||
)
|
||||
|
||||
function RouteComponent() {
|
||||
const { directoryId } = Route.useParams()
|
||||
const rootDirectory = useConvexQuery(api.files.fetchRootDirectory)
|
||||
const directory = useConvexQuery(api.files.fetchDirectory, {
|
||||
directoryId,
|
||||
})
|
||||
const directoryContent = useConvexQuery(
|
||||
api.filesystem.fetchDirectoryContent,
|
||||
{
|
||||
directoryId,
|
||||
trashed: true,
|
||||
},
|
||||
)
|
||||
const setContextMenuTargetItems = useSetAtom(contextMenuTargetItemsAtom)
|
||||
const setOpenedFile = useSetAtom(openedFileAtom)
|
||||
|
||||
const directoryUrlFn = useCallback(
|
||||
(directory: Doc<"directories">) =>
|
||||
`/trash/directories/${directory._id}`,
|
||||
[],
|
||||
)
|
||||
|
||||
const directoryUrlById = useCallback(
|
||||
(directoryId: Id<"directories">) => `/trash/directories/${directoryId}`,
|
||||
[],
|
||||
)
|
||||
|
||||
if (!directory || !directoryContent || !rootDirectory) {
|
||||
return <DirectoryPageSkeleton />
|
||||
}
|
||||
|
||||
const handleContextMenuRequest = (
|
||||
row: Row<FileSystemItem>,
|
||||
table: Table<FileSystemItem>,
|
||||
) => {
|
||||
if (row.getIsSelected()) {
|
||||
setContextMenuTargetItems(
|
||||
table.getSelectedRowModel().rows.map((row) => row.original),
|
||||
)
|
||||
} else {
|
||||
setContextMenuTargetItems([row.original])
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<DirectoryPageContext
|
||||
value={{ rootDirectory, directory, directoryContent }}
|
||||
>
|
||||
<header className="flex py-2 shrink-0 items-center gap-2 border-b px-4 w-full">
|
||||
<FilePathBreadcrumb
|
||||
rootLabel="Trash"
|
||||
directoryUrlFn={directoryUrlById}
|
||||
/>
|
||||
<div className="ml-auto flex flex-row gap-2">
|
||||
<EmptyTrashButton />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<TableContextMenu>
|
||||
<div className="w-full">
|
||||
<DirectoryContentTable
|
||||
filterFn={() => true}
|
||||
directoryUrlFn={directoryUrlFn}
|
||||
fileDragInfoAtom={fileDragInfoAtom}
|
||||
onContextMenu={handleContextMenuRequest}
|
||||
onOpenFile={setOpenedFile}
|
||||
/>
|
||||
</div>
|
||||
</TableContextMenu>
|
||||
|
||||
<DeleteConfirmationDialog />
|
||||
<EmptyTrashConfirmationDialog />
|
||||
|
||||
<WithAtom atom={openedFileAtom}>
|
||||
{(openedFile, setOpenedFile) => {
|
||||
if (!openedFile) return null
|
||||
return (
|
||||
<FilePreviewDialog
|
||||
file={openedFile}
|
||||
onClose={() => setOpenedFile(null)}
|
||||
/>
|
||||
)
|
||||
}}
|
||||
</WithAtom>
|
||||
</DirectoryPageContext>
|
||||
)
|
||||
}
|
||||
|
||||
function TableContextMenu({ children }: React.PropsWithChildren) {
|
||||
const setActiveDialog = useSetAtom(activeDialogAtom)
|
||||
|
||||
return (
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
|
||||
<ContextMenuContent>
|
||||
<RestoreContextMenuItem />
|
||||
<ContextMenuItem
|
||||
variant="destructive"
|
||||
onClick={() => {
|
||||
setActiveDialog(ActiveDialogKind.DeleteConfirmation)
|
||||
}}
|
||||
>
|
||||
<ShredderIcon />
|
||||
Delete permanently
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
|
||||
function RestoreContextMenuItem() {
|
||||
const store = useStore()
|
||||
const setOptimisticRemovedItems = useSetAtom(optimisticRemovedItemsAtom)
|
||||
const restoreItemsMutation = useConvexMutation(api.filesystem.restoreItems)
|
||||
const { mutate: restoreItems, isPending: isRestoring } = useMutation({
|
||||
mutationFn: restoreItemsMutation,
|
||||
onMutate: ({ handles }) => {
|
||||
setOptimisticRemovedItems(
|
||||
new Set(handles.map((handle) => handle.id)),
|
||||
)
|
||||
},
|
||||
onSuccess: ({ restored, errors }) => {
|
||||
if (errors.length === 0) {
|
||||
if (restored.files > 0 && restored.directories > 0) {
|
||||
toast.success(
|
||||
`Restored ${restored.files} files and ${restored.directories} directories`,
|
||||
)
|
||||
} else if (restored.files > 0) {
|
||||
toast.success(`Restored ${restored.files} files`)
|
||||
} else if (restored.directories > 0) {
|
||||
toast.success(
|
||||
`Restored ${restored.directories} directories`,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
toast.warning(
|
||||
`Restored ${restored.files} files and ${restored.directories} directories; failed to restore ${errors.length} items`,
|
||||
)
|
||||
}
|
||||
},
|
||||
})
|
||||
const setBackgroundTaskProgress = useSetAtom(backgroundTaskProgressAtom)
|
||||
|
||||
useEffect(() => {
|
||||
if (isRestoring) {
|
||||
setBackgroundTaskProgress({
|
||||
label: "Restoring items…",
|
||||
})
|
||||
} else {
|
||||
setBackgroundTaskProgress(null)
|
||||
}
|
||||
}, [isRestoring, setBackgroundTaskProgress])
|
||||
|
||||
const onClick = () => {
|
||||
const targetItems = store.get(contextMenuTargetItemsAtom)
|
||||
restoreItems({
|
||||
handles: targetItems.map(newFileSystemHandle),
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<ContextMenuItem onClick={onClick}>
|
||||
<UndoIcon />
|
||||
Restore
|
||||
</ContextMenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyTrashButton() {
|
||||
const setActiveDialog = useSetAtom(activeDialogAtom)
|
||||
|
||||
return (
|
||||
<Button
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="destructive"
|
||||
onClick={() => {
|
||||
setActiveDialog(ActiveDialogKind.EmptyTrashConfirmation)
|
||||
}}
|
||||
>
|
||||
<TrashIcon className="size-4" />
|
||||
Empty trash
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function DeleteConfirmationDialog() {
|
||||
const { rootDirectory } = useContext(DirectoryPageContext)
|
||||
const [activeDialog, setActiveDialog] = useAtom(activeDialogAtom)
|
||||
const [targetItems, setTargetItems] = useAtom(contextMenuTargetItemsAtom)
|
||||
const setOptimisticRemovedItems = useSetAtom(optimisticRemovedItemsAtom)
|
||||
|
||||
const deletePermanentlyMutation = useConvexMutation(
|
||||
api.filesystem.permanentlyDeleteItems,
|
||||
)
|
||||
const { mutate: deletePermanently, isPending: isDeleting } = useMutation({
|
||||
mutationFn: deletePermanentlyMutation,
|
||||
onMutate: ({ handles }) => {
|
||||
setOptimisticRemovedItems(
|
||||
(prev) =>
|
||||
new Set([...prev, ...handles.map((handle) => handle.id)]),
|
||||
)
|
||||
},
|
||||
onSuccess: ({ deleted, errors }, { handles }) => {
|
||||
setOptimisticRemovedItems((prev) => {
|
||||
const newSet = new Set(prev)
|
||||
for (const handle of handles) {
|
||||
newSet.delete(handle.id)
|
||||
}
|
||||
return newSet
|
||||
})
|
||||
if (errors.length === 0) {
|
||||
toast.success(
|
||||
`Deleted ${deleted.files} files and ${deleted.directories} directories`,
|
||||
)
|
||||
} else {
|
||||
toast.warning(
|
||||
`Deleted ${deleted.files} files and ${deleted.directories} directories; failed to delete ${errors.length} items`,
|
||||
)
|
||||
}
|
||||
setActiveDialog(null)
|
||||
setTargetItems([])
|
||||
},
|
||||
})
|
||||
|
||||
const onOpenChange = (open: boolean) => {
|
||||
if (open) {
|
||||
setActiveDialog(ActiveDialogKind.DeleteConfirmation)
|
||||
} else {
|
||||
setActiveDialog(null)
|
||||
}
|
||||
}
|
||||
|
||||
const confirmDelete = () => {
|
||||
deletePermanently({
|
||||
handles:
|
||||
targetItems.length > 0
|
||||
? targetItems.map(newFileSystemHandle)
|
||||
: [
|
||||
newFileSystemHandle({
|
||||
kind: FileType.Directory,
|
||||
doc: rootDirectory,
|
||||
}),
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={activeDialog === ActiveDialogKind.DeleteConfirmation}
|
||||
onOpenChange={onOpenChange}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
Permanently delete {targetItems.length} items?
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<p>
|
||||
{targetItems.length} items will be permanently deleted. They
|
||||
will be IRRECOVERABLE.
|
||||
</p>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button variant="outline" disabled={isDeleting}>
|
||||
Go back
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={confirmDelete}
|
||||
disabled={isDeleting}
|
||||
loading={isDeleting}
|
||||
>
|
||||
Yes, delete
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyTrashConfirmationDialog() {
|
||||
const [activeDialog, setActiveDialog] = useAtom(activeDialogAtom)
|
||||
|
||||
const { mutate: emptyTrash, isPending: isEmptying } = useMutation({
|
||||
mutationFn: useConvexMutation(api.filesystem.emptyTrash),
|
||||
onSuccess: () => {
|
||||
toast.success("Trash emptied successfully")
|
||||
setActiveDialog(null)
|
||||
},
|
||||
})
|
||||
|
||||
function onOpenChange(open: boolean) {
|
||||
if (open) {
|
||||
setActiveDialog(ActiveDialogKind.EmptyTrashConfirmation)
|
||||
} else {
|
||||
setActiveDialog(null)
|
||||
}
|
||||
}
|
||||
|
||||
function confirmEmpty() {
|
||||
emptyTrash(undefined)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={activeDialog === ActiveDialogKind.EmptyTrashConfirmation}
|
||||
onOpenChange={onOpenChange}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Empty your trash?</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<p>
|
||||
All items in the trash will be permanently deleted. They
|
||||
will be IRRECOVERABLE.
|
||||
</p>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button variant="outline" disabled={isEmptying}>
|
||||
No, go back
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={confirmEmpty}
|
||||
disabled={isEmptying}
|
||||
loading={isEmptying}
|
||||
>
|
||||
Yes, empty trash
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { createFileRoute, Navigate } from "@tanstack/react-router"
|
||||
|
||||
export const Route = createFileRoute("/_authenticated/")({
|
||||
component: RouteComponent,
|
||||
})
|
||||
|
||||
function RouteComponent() {
|
||||
return <Navigate replace to="/home" />
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
import { GalleryVerticalEnd } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card"
|
||||
import {
|
||||
Field,
|
||||
FieldDescription,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
FieldSeparator,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { type AuthErrorCode, authClient, BetterAuthError } from "../auth"
|
||||
|
||||
export const Route = createFileRoute("/login")({
|
||||
component: RouteComponent,
|
||||
})
|
||||
|
||||
function RouteComponent() {
|
||||
return (
|
||||
<div className="bg-background flex min-h-svh flex-col items-center justify-center gap-6 p-6 md:p-10">
|
||||
<div className="flex w-full max-w-lg flex-col gap-6">
|
||||
<a
|
||||
href="#"
|
||||
className="flex items-center gap-2 self-center font-medium text-xl"
|
||||
>
|
||||
<div className="bg-primary text-primary-foreground flex size-6 items-center justify-center rounded-md">
|
||||
<GalleryVerticalEnd className="size-4" />
|
||||
</div>
|
||||
Drexa
|
||||
</a>
|
||||
<LoginFormCard />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function LoginFormCard({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div className={cn("flex flex-col gap-6", className)} {...props}>
|
||||
<Card>
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="text-xl">Welcome back</CardTitle>
|
||||
<CardDescription>
|
||||
Login with your Apple or Google account
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoginForm />
|
||||
</CardContent>
|
||||
</Card>
|
||||
<FieldDescription className="px-6 text-center">
|
||||
By clicking continue, you agree to our{" "}
|
||||
<a href="#">Terms of Service</a> and{" "}
|
||||
<a href="#">Privacy Policy</a>.
|
||||
</FieldDescription>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function LoginForm() {
|
||||
const {
|
||||
mutate: signIn,
|
||||
isPending,
|
||||
error: signInError,
|
||||
} = useMutation({
|
||||
mutationFn: async ({
|
||||
email,
|
||||
password,
|
||||
}: {
|
||||
email: string
|
||||
password: string
|
||||
}) => {
|
||||
const { data: signInData, error } = await authClient.signIn.email({
|
||||
email,
|
||||
password,
|
||||
callbackURL: "/home",
|
||||
rememberMe: true,
|
||||
})
|
||||
if (error) {
|
||||
throw new BetterAuthError(error.code as AuthErrorCode)
|
||||
}
|
||||
return signInData
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
const formData = new FormData(event.currentTarget)
|
||||
signIn({
|
||||
email: formData.get("email") as string,
|
||||
password: formData.get("password") as string,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit}>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<Button
|
||||
disabled={isPending}
|
||||
variant="outline"
|
||||
type="button"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<title>Apple logo</title>
|
||||
<path
|
||||
d="M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
Login with Apple
|
||||
</Button>
|
||||
<Button
|
||||
disabled={isPending}
|
||||
variant="outline"
|
||||
type="button"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<title>Google logo</title>
|
||||
<path
|
||||
d="M12.48 10.92v3.28h7.84c-.24 1.84-.853 3.187-1.787 4.133-1.147 1.147-2.933 2.4-6.053 2.4-4.827 0-8.6-3.893-8.6-8.72s3.773-8.72 8.6-8.72c2.6 0 4.507 1.027 5.907 2.347l2.307-2.307C18.747 1.44 16.133 0 12.48 0 5.867 0 .307 5.387.307 12s5.56 12 12.173 12c3.573 0 6.267-1.173 8.373-3.36 2.16-2.16 2.84-5.213 2.84-7.667 0-.76-.053-1.467-.173-2.053H12.48z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
Login with Google
|
||||
</Button>
|
||||
</Field>
|
||||
<FieldSeparator className="*:data-[slot=field-separator-content]:bg-card">
|
||||
Or continue with
|
||||
</FieldSeparator>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<Input
|
||||
disabled={isPending}
|
||||
name="email"
|
||||
type="email"
|
||||
placeholder="m@example.com"
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<div className="flex items-center">
|
||||
<FieldLabel htmlFor="password">Password</FieldLabel>
|
||||
<a
|
||||
href="#"
|
||||
className="ml-auto text-sm underline-offset-4 hover:underline"
|
||||
>
|
||||
Forgot your password?
|
||||
</a>
|
||||
</div>
|
||||
<Input
|
||||
disabled={isPending}
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<Button disabled={isPending} type="submit">
|
||||
{isPending ? "Logging in…" : "Login"}
|
||||
</Button>
|
||||
<FieldDescription className="text-center">
|
||||
Don't have an account? <a href="#">Sign up</a>
|
||||
</FieldDescription>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { createFileRoute, useNavigate } from "@tanstack/react-router"
|
||||
import { useConvexAuth, useMutation as useConvexMutation } from "convex/react"
|
||||
import { useEffect } from "react"
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner"
|
||||
|
||||
export const Route = createFileRoute("/login_/callback")({
|
||||
component: RouteComponent,
|
||||
})
|
||||
|
||||
function RouteComponent() {
|
||||
const { isLoading: isLoadingConvexAuth, isAuthenticated } = useConvexAuth()
|
||||
const { mutate: syncUser, isPending: isSyncingUser } = useMutation({
|
||||
mutationFn: useConvexMutation(api.users.syncUser),
|
||||
retry: true,
|
||||
})
|
||||
const navigate = useNavigate()
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoadingConvexAuth && isAuthenticated && !isSyncingUser) {
|
||||
syncUser(undefined, {
|
||||
onSuccess: () => {
|
||||
navigate({
|
||||
to: "/",
|
||||
replace: true,
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
}, [
|
||||
isLoadingConvexAuth,
|
||||
isAuthenticated,
|
||||
syncUser,
|
||||
isSyncingUser,
|
||||
navigate,
|
||||
])
|
||||
|
||||
return (
|
||||
<div className="flex h-screen w-full items-center justify-center">
|
||||
<LoadingSpinner className="size-10" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { createFileRoute, useNavigate } from "@tanstack/react-router"
|
||||
import { GalleryVerticalEnd } from "lucide-react"
|
||||
import type React from "react"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card"
|
||||
import {
|
||||
Field,
|
||||
FieldDescription,
|
||||
FieldError,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { type AuthErrorCode, authClient, BetterAuthError } from "../auth"
|
||||
|
||||
export const Route = createFileRoute("/sign-up")({
|
||||
component: SignupPage,
|
||||
})
|
||||
|
||||
type SignUpParams = {
|
||||
displayName: string
|
||||
email: string
|
||||
password: string
|
||||
confirmPassword: string
|
||||
}
|
||||
|
||||
class PasswordMismatchError extends Error {
|
||||
constructor() {
|
||||
super("Passwords do not match")
|
||||
}
|
||||
}
|
||||
|
||||
function SignupPage() {
|
||||
return (
|
||||
<div className="bg-background flex min-h-svh flex-col items-center justify-center gap-6 p-6 md:p-10">
|
||||
<div className="flex w-full max-w-xl flex-col gap-6">
|
||||
<a
|
||||
href="#"
|
||||
className="flex items-center gap-2 self-center font-medium text-xl"
|
||||
>
|
||||
<div className="bg-primary text-primary-foreground flex size-6 items-center justify-center rounded-md">
|
||||
<GalleryVerticalEnd className="size-4" />
|
||||
</div>
|
||||
Drexa
|
||||
</a>
|
||||
<SignUpFormContainer>
|
||||
<SignupForm />
|
||||
</SignUpFormContainer>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SignUpFormContainer({ children }: React.PropsWithChildren) {
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<Card>
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="text-xl">
|
||||
Create your account
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Enter your email below to create your account
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>{children}</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SignupForm() {
|
||||
const navigate = useNavigate()
|
||||
const {
|
||||
mutate: signUp,
|
||||
isPending,
|
||||
error: signUpError,
|
||||
} = useMutation({
|
||||
mutationFn: async (data: SignUpParams) => {
|
||||
if (data.password !== data.confirmPassword) {
|
||||
throw new PasswordMismatchError()
|
||||
}
|
||||
const { data: signUpData, error } = await authClient.signUp.email({
|
||||
name: data.displayName,
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
})
|
||||
if (error) {
|
||||
throw new BetterAuthError(error.code as AuthErrorCode)
|
||||
}
|
||||
return signUpData
|
||||
},
|
||||
onSuccess: () => {
|
||||
navigate({
|
||||
to: "/",
|
||||
replace: true,
|
||||
})
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error(error)
|
||||
toast.error("Unable to create your account")
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
const formData = new FormData(event.currentTarget)
|
||||
signUp({
|
||||
displayName: formData.get("displayName") as string,
|
||||
email: formData.get("email") as string,
|
||||
password: formData.get("password") as string,
|
||||
confirmPassword: formData.get("confirmPassword") as string,
|
||||
})
|
||||
}
|
||||
|
||||
let passwordFieldError = null
|
||||
let emailFieldError = null
|
||||
if (signUpError instanceof BetterAuthError) {
|
||||
switch (signUpError.errorCode) {
|
||||
case "PASSWORD_TOO_SHORT":
|
||||
passwordFieldError =
|
||||
"Password must be at least 8 characters long"
|
||||
break
|
||||
case "INVALID_EMAIL":
|
||||
emailFieldError = "Invalid email address"
|
||||
break
|
||||
default:
|
||||
passwordFieldError = null
|
||||
}
|
||||
} else if (signUpError instanceof PasswordMismatchError) {
|
||||
passwordFieldError = "Passwords do not match"
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit}>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="name">Your Name</FieldLabel>
|
||||
<Input
|
||||
disabled={isPending}
|
||||
name="displayName"
|
||||
type="text"
|
||||
placeholder="John Doe"
|
||||
required
|
||||
/>
|
||||
<FieldDescription>
|
||||
This is how you will be referred to on Drexa. You can
|
||||
change this later.
|
||||
</FieldDescription>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<Input
|
||||
disabled={isPending}
|
||||
name="email"
|
||||
type="email"
|
||||
placeholder="m@example.com"
|
||||
required
|
||||
/>
|
||||
{emailFieldError ? (
|
||||
<FieldError>{emailFieldError}</FieldError>
|
||||
) : null}
|
||||
</Field>
|
||||
<Field>
|
||||
<Field className="grid grid-rows-2 md:grid-rows-1 md:grid-cols-2 gap-4">
|
||||
<Field>
|
||||
<FieldLabel htmlFor="password">Password</FieldLabel>
|
||||
<Input
|
||||
disabled={isPending}
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="confirm-password">
|
||||
Confirm Password
|
||||
</FieldLabel>
|
||||
<Input
|
||||
disabled={isPending}
|
||||
name="confirmPassword"
|
||||
type="password"
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
</Field>
|
||||
{passwordFieldError ? (
|
||||
<FieldError>{passwordFieldError}</FieldError>
|
||||
) : (
|
||||
<FieldDescription>
|
||||
Must be at least 8 characters long.
|
||||
</FieldDescription>
|
||||
)}
|
||||
</Field>
|
||||
<Field>
|
||||
<Button
|
||||
type="submit"
|
||||
loading={isPending}
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending ? "Creating account…" : "Create Account"}
|
||||
</Button>
|
||||
<FieldDescription className="text-center">
|
||||
Already have an account? <a href="/sign-in">Sign in</a>
|
||||
</FieldDescription>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { serve } from "bun"
|
||||
import index from "./index.html"
|
||||
|
||||
const server = serve({
|
||||
port: process.env.PORT || 3001,
|
||||
routes: {
|
||||
// Serve index.html for all unmatched routes.
|
||||
"/*": index,
|
||||
},
|
||||
|
||||
development: process.env.NODE_ENV !== "production" && {
|
||||
// Enable browser hot reloading in development
|
||||
hmr: true,
|
||||
|
||||
// Echo console logs from the browser to the server
|
||||
console: true,
|
||||
},
|
||||
})
|
||||
|
||||
console.log(`🚀 Server running at ${server.url}`)
|
||||
@@ -1,121 +0,0 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
:root {
|
||||
--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);
|
||||
--radius: 0.625rem;
|
||||
--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);
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--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-destructive-foreground: var(--destructive-foreground);
|
||||
--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);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--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);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
// Environment setup & latest features
|
||||
"lib": ["ESNext", "DOM"],
|
||||
"target": "ESNext",
|
||||
"module": "Preserve",
|
||||
"moduleDetection": "force",
|
||||
"jsx": "react-jsx",
|
||||
"allowJs": true,
|
||||
|
||||
// Bundler mode
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"noEmit": true,
|
||||
|
||||
// Best practices
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
|
||||
// Some stricter flags (disabled by default)
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noPropertyAccessFromIndexSignature": false
|
||||
},
|
||||
|
||||
"exclude": ["dist", "node_modules"]
|
||||
}
|
||||
Reference in New Issue
Block a user