refactor: top level dir + moved route
create a root directory entry in table for each user and move file browser under /directories/$id
This commit is contained in:
@@ -26,6 +26,21 @@ export const fetchFiles = authenticatedQuery({
|
||||
},
|
||||
})
|
||||
|
||||
export const fetchRootDirectory = authenticatedQuery({
|
||||
handler: async (ctx) => {
|
||||
return await Directories.fetchRoot(ctx)
|
||||
},
|
||||
})
|
||||
|
||||
export const fetchDirectory = authenticatedQuery({
|
||||
args: {
|
||||
directoryId: v.id("directories"),
|
||||
},
|
||||
handler: async (ctx, { directoryId }) => {
|
||||
return await Directories.fetch(ctx, { directoryId })
|
||||
},
|
||||
})
|
||||
|
||||
export const fetchDirectoryContent = authenticatedQuery({
|
||||
args: {
|
||||
directoryId: v.optional(v.id("directories")),
|
||||
@@ -39,7 +54,7 @@ export const fetchDirectoryContent = authenticatedQuery({
|
||||
export const createDirectory = authenticatedMutation({
|
||||
args: {
|
||||
name: v.string(),
|
||||
directoryId: v.optional(v.id("directories")),
|
||||
directoryId: v.id("directories"),
|
||||
},
|
||||
handler: async (ctx, { name, directoryId }): Promise<Id<"directories">> => {
|
||||
return await Directories.create(ctx, {
|
||||
|
@@ -19,6 +19,22 @@ type File = {
|
||||
export type DirectoryItem = Directory | File
|
||||
export type DirectoryItemKind = DirectoryItem["kind"]
|
||||
|
||||
export async function fetchRoot(ctx: AuthenticatedQueryCtx) {
|
||||
return await ctx.db
|
||||
.query("directories")
|
||||
.withIndex("byParentId", (q) =>
|
||||
q.eq("userId", ctx.user._id).eq("parentId", undefined),
|
||||
)
|
||||
.first()
|
||||
}
|
||||
|
||||
export async function fetch(
|
||||
ctx: AuthenticatedQueryCtx,
|
||||
{ directoryId }: { directoryId: Id<"directories"> },
|
||||
) {
|
||||
return await ctx.db.get(directoryId)
|
||||
}
|
||||
|
||||
export async function fetchContent(
|
||||
ctx: AuthenticatedQueryCtx,
|
||||
{
|
||||
@@ -76,17 +92,14 @@ export async function fetchContent(
|
||||
|
||||
export async function create(
|
||||
ctx: AuthenticatedMutationCtx,
|
||||
{ name, parentId }: { name: string; parentId?: Id<"directories"> },
|
||||
{ name, parentId }: { name: string; parentId: Id<"directories"> },
|
||||
): Promise<Id<"directories">> {
|
||||
let parentDir: Doc<"directories"> | null = null
|
||||
if (parentId) {
|
||||
parentDir = await ctx.db.get(parentId)
|
||||
if (!parentDir) {
|
||||
throw Err.create(
|
||||
Err.Code.DirectoryNotFound,
|
||||
`Parent directory ${parentId} not found`,
|
||||
)
|
||||
}
|
||||
const parentDir = await ctx.db.get(parentId)
|
||||
if (!parentDir) {
|
||||
throw Err.create(
|
||||
Err.Code.DirectoryNotFound,
|
||||
`Parent directory ${parentId} not found`,
|
||||
)
|
||||
}
|
||||
|
||||
const existing = await ctx.db
|
||||
|
@@ -1,4 +1,3 @@
|
||||
import type { Id } from "../_generated/dataModel"
|
||||
import type { MutationCtx, QueryCtx } from "../_generated/server"
|
||||
import type { AuthenticatedMutationCtx } from "../functions"
|
||||
import * as Err from "./error"
|
||||
@@ -40,7 +39,17 @@ export async function userOrThrow(ctx: QueryCtx | MutationCtx) {
|
||||
}
|
||||
|
||||
export async function register(ctx: AuthenticatedMutationCtx) {
|
||||
await ctx.db.insert("users", {
|
||||
jwtSubject: ctx.identity.subject,
|
||||
})
|
||||
const now = new Date().toISOString()
|
||||
await Promise.all([
|
||||
ctx.db.insert("users", {
|
||||
jwtSubject: ctx.identity.subject,
|
||||
}),
|
||||
ctx.db.insert("directories", {
|
||||
name: "",
|
||||
path: "",
|
||||
userId: ctx.user._id,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}),
|
||||
])
|
||||
}
|
||||
|
@@ -1,5 +1,7 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import { Link, useLocation } from "@tanstack/react-router"
|
||||
import { useAuth } from "@workos-inc/authkit-react"
|
||||
import { useQuery as useConvexQuery } from "convex/react"
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
FilesIcon,
|
||||
@@ -59,18 +61,34 @@ function MainSidebarMenu() {
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton asChild isActive={isActive("/files")}>
|
||||
<Link to="/files">
|
||||
<FilesIcon />
|
||||
<span>All Files</span>
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
<AllFilesItem />
|
||||
</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/${rootDirectory._id}`,
|
||||
)}
|
||||
>
|
||||
<Link to={`/directories/${rootDirectory._id}`}>
|
||||
<FilesIcon />
|
||||
<span>All Files</span>
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
function UserMenu() {
|
||||
const { signOut } = useAuth()
|
||||
|
||||
|
12
packages/web/src/directories/directory-page/context.ts
Normal file
12
packages/web/src/directories/directory-page/context.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import type { Doc } from "@fileone/convex/_generated/dataModel"
|
||||
import type { DirectoryItem } from "@fileone/convex/model/directories"
|
||||
import { createContext } from "react"
|
||||
|
||||
type DirectoryPageContextType = {
|
||||
directory: Doc<"directories">
|
||||
directoryContent: DirectoryItem[]
|
||||
}
|
||||
|
||||
export const DirectoryPageContext = createContext<DirectoryPageContextType>(
|
||||
null as unknown as DirectoryPageContextType,
|
||||
)
|
@@ -0,0 +1,68 @@
|
||||
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>
|
||||
)
|
||||
}
|
@@ -0,0 +1,423 @@
|
||||
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 } from "convex/react"
|
||||
import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai"
|
||||
import { CheckIcon, TextCursorInputIcon, TrashIcon, XIcon } from "lucide-react"
|
||||
import { useContext, 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 { DirectoryPageContext } from "./context"
|
||||
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 DirectoryContentTable() {
|
||||
return (
|
||||
<DirectoryContentTableContextMenu>
|
||||
<div className="w-full">
|
||||
<DirectoryContentTableContent />
|
||||
</div>
|
||||
</DirectoryContentTableContextMenu>
|
||||
)
|
||||
}
|
||||
|
||||
export function DirectoryContentTableContextMenu({
|
||||
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 DirectoryContentTableContent() {
|
||||
const { directoryContent } = useContext(DirectoryPageContext)
|
||||
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: directoryContent || [],
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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 { directory } = useContext(DirectoryPageContext)
|
||||
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, directoryId: directory._id })
|
||||
} 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={`/directories/${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>
|
||||
)
|
||||
}
|
@@ -0,0 +1,44 @@
|
||||
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>
|
||||
)
|
||||
}
|
181
packages/web/src/directories/directory-page/directory-page.tsx
Normal file
181
packages/web/src/directories/directory-page/directory-page.tsx
Normal file
@@ -0,0 +1,181 @@
|
||||
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, useContext, 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 { DirectoryPageContext } from "./context"
|
||||
import { DirectoryContentTable } from "./directory-content-table"
|
||||
import { RenameFileDialog } from "./rename-file-dialog"
|
||||
import { newItemKindAtom } from "./state"
|
||||
|
||||
export function DirectoryPage() {
|
||||
const { directory } = useContext(DirectoryPageContext)
|
||||
return (
|
||||
<>
|
||||
<header className="flex py-1 shrink-0 items-center gap-2 border-b px-4 w-full">
|
||||
<FilePathBreadcrumb path={directory.path} />
|
||||
<div className="ml-auto flex flex-row gap-2">
|
||||
<NewDirectoryItemDropdown />
|
||||
<UploadFileButton />
|
||||
</div>
|
||||
</header>
|
||||
<div className="w-full">
|
||||
<DirectoryContentTable />
|
||||
</div>
|
||||
<RenameFileDialog />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function FilePathBreadcrumb({ path }: { path: string }) {
|
||||
const pathComponents = splitPath(path)
|
||||
const base = baseName(path)
|
||||
return (
|
||||
<Breadcrumb>
|
||||
<BreadcrumbList>
|
||||
<BreadcrumbItem>
|
||||
<BreadcrumbLink asChild>
|
||||
<Link to="/directories">All Files</Link>
|
||||
</BreadcrumbLink>
|
||||
</BreadcrumbItem>
|
||||
{pathComponents.map((p) => (
|
||||
<Fragment key={p}>
|
||||
<BreadcrumbSeparator />
|
||||
{p === base ? (
|
||||
<BreadcrumbPage>{p}</BreadcrumbPage>
|
||||
) : (
|
||||
<BreadcrumbItem>
|
||||
<BreadcrumbLink asChild>
|
||||
<Link to={`/directories/${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>
|
||||
)
|
||||
}
|
@@ -0,0 +1,111 @@
|
||||
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)}
|
||||
/>
|
||||
)
|
||||
}
|
@@ -0,0 +1,42 @@
|
||||
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>
|
||||
)
|
||||
}
|
22
packages/web/src/directories/directory-page/state.ts
Normal file
22
packages/web/src/directories/directory-page/state.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
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)
|
@@ -15,6 +15,7 @@ import { Route as AuthenticatedIndexRouteImport } from './routes/_authenticated/
|
||||
import { Route as LoginCallbackRouteImport } from './routes/login_.callback'
|
||||
import { Route as AuthenticatedSidebarLayoutRouteImport } from './routes/_authenticated/_sidebar-layout'
|
||||
import { Route as AuthenticatedSidebarLayoutFilesSplatRouteImport } from './routes/_authenticated/_sidebar-layout/files.$'
|
||||
import { Route as AuthenticatedSidebarLayoutDirectoriesDirectoryIdRouteImport } from './routes/_authenticated/_sidebar-layout/directories.$directoryId'
|
||||
|
||||
const LoginRoute = LoginRouteImport.update({
|
||||
id: '/login',
|
||||
@@ -46,17 +47,25 @@ const AuthenticatedSidebarLayoutFilesSplatRoute =
|
||||
path: '/files/$',
|
||||
getParentRoute: () => AuthenticatedSidebarLayoutRoute,
|
||||
} as any)
|
||||
const AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute =
|
||||
AuthenticatedSidebarLayoutDirectoriesDirectoryIdRouteImport.update({
|
||||
id: '/directories/$directoryId',
|
||||
path: '/directories/$directoryId',
|
||||
getParentRoute: () => AuthenticatedSidebarLayoutRoute,
|
||||
} as any)
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/login': typeof LoginRoute
|
||||
'/login/callback': typeof LoginCallbackRoute
|
||||
'/': typeof AuthenticatedIndexRoute
|
||||
'/directories/$directoryId': typeof AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute
|
||||
'/files/$': typeof AuthenticatedSidebarLayoutFilesSplatRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/login': typeof LoginRoute
|
||||
'/login/callback': typeof LoginCallbackRoute
|
||||
'/': typeof AuthenticatedIndexRoute
|
||||
'/directories/$directoryId': typeof AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute
|
||||
'/files/$': typeof AuthenticatedSidebarLayoutFilesSplatRoute
|
||||
}
|
||||
export interface FileRoutesById {
|
||||
@@ -66,13 +75,24 @@ export interface FileRoutesById {
|
||||
'/_authenticated/_sidebar-layout': typeof AuthenticatedSidebarLayoutRouteWithChildren
|
||||
'/login_/callback': typeof LoginCallbackRoute
|
||||
'/_authenticated/': typeof AuthenticatedIndexRoute
|
||||
'/_authenticated/_sidebar-layout/directories/$directoryId': typeof AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute
|
||||
'/_authenticated/_sidebar-layout/files/$': typeof AuthenticatedSidebarLayoutFilesSplatRoute
|
||||
}
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths: '/login' | '/login/callback' | '/' | '/files/$'
|
||||
fullPaths:
|
||||
| '/login'
|
||||
| '/login/callback'
|
||||
| '/'
|
||||
| '/directories/$directoryId'
|
||||
| '/files/$'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to: '/login' | '/login/callback' | '/' | '/files/$'
|
||||
to:
|
||||
| '/login'
|
||||
| '/login/callback'
|
||||
| '/'
|
||||
| '/directories/$directoryId'
|
||||
| '/files/$'
|
||||
id:
|
||||
| '__root__'
|
||||
| '/_authenticated'
|
||||
@@ -80,6 +100,7 @@ export interface FileRouteTypes {
|
||||
| '/_authenticated/_sidebar-layout'
|
||||
| '/login_/callback'
|
||||
| '/_authenticated/'
|
||||
| '/_authenticated/_sidebar-layout/directories/$directoryId'
|
||||
| '/_authenticated/_sidebar-layout/files/$'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
@@ -133,15 +154,25 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof AuthenticatedSidebarLayoutFilesSplatRouteImport
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface AuthenticatedSidebarLayoutRouteChildren {
|
||||
AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute: typeof AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute
|
||||
AuthenticatedSidebarLayoutFilesSplatRoute: typeof AuthenticatedSidebarLayoutFilesSplatRoute
|
||||
}
|
||||
|
||||
const AuthenticatedSidebarLayoutRouteChildren: AuthenticatedSidebarLayoutRouteChildren =
|
||||
{
|
||||
AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute:
|
||||
AuthenticatedSidebarLayoutDirectoriesDirectoryIdRoute,
|
||||
AuthenticatedSidebarLayoutFilesSplatRoute:
|
||||
AuthenticatedSidebarLayoutFilesSplatRoute,
|
||||
}
|
||||
|
@@ -1,4 +1,5 @@
|
||||
import { createFileRoute, Outlet } from "@tanstack/react-router"
|
||||
import { useQuery as useConvexQuery } from "convex/react"
|
||||
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
|
||||
import { Toaster } from "@/components/ui/sonner"
|
||||
import { DashboardSidebar } from "@/dashboard/dashboard-sidebar"
|
||||
|
@@ -0,0 +1,32 @@
|
||||
import { api } from "@fileone/convex/_generated/api"
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
import { useQuery as useConvexQuery } from "convex/react"
|
||||
import { DirectoryPageContext } from "@/directories/directory-page/context"
|
||||
import { DirectoryPage } from "@/directories/directory-page/directory-page"
|
||||
import { DirectoryPageSkeleton } from "@/directories/directory-page/directory-page-skeleton"
|
||||
|
||||
export const Route = createFileRoute(
|
||||
"/_authenticated/_sidebar-layout/directories/$directoryId",
|
||||
)({
|
||||
component: RouteComponent,
|
||||
})
|
||||
|
||||
function RouteComponent() {
|
||||
const { directoryId } = Route.useParams()
|
||||
const directory = useConvexQuery(api.files.fetchDirectory, {
|
||||
directoryId,
|
||||
})
|
||||
const directoryContent = useConvexQuery(api.files.fetchDirectoryContent, {
|
||||
directoryId,
|
||||
})
|
||||
|
||||
if (!directory || !directoryContent) {
|
||||
return <DirectoryPageSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<DirectoryPageContext value={{ directory, directoryContent }}>
|
||||
<DirectoryPage />
|
||||
</DirectoryPageContext>
|
||||
)
|
||||
}
|
Reference in New Issue
Block a user