Skip to content

Commit

Permalink
Fixed revision preview in client component from data table context
Browse files Browse the repository at this point in the history
  • Loading branch information
FlorianLeChat committed Jan 11, 2024
1 parent f0acd8e commit 874199c
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 28 deletions.
9 changes: 6 additions & 3 deletions app/[locale]/dashboard/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,12 +335,14 @@ export async function uploadFiles(
// fichiers sous format JSON pour pouvoir les envoyer
// à travers le réseau vers les composants clients.
// Source : https://github.com/vercel/next.js/issues/47447
const path = `${ process.env.__NEXT_ROUTER_BASEPATH }/d/${ fileId }`;

return JSON.stringify( {
uuid: fileId,
name: parse( file.name ).name,
size: file.size,
type: file.type,
path: `${ process.env.__NEXT_ROUTER_BASEPATH }/d/${ fileId }`,
path,
versions: (
await prisma.version.findMany( {
where: {
Expand All @@ -352,8 +354,9 @@ export async function uploadFiles(
} )
).map( ( version ) => ( {
uuid: version.id,
size: version.size,
date: version.createdAt.toLocaleString()
size: Number( version.size ),
date: version.createdAt.toLocaleString(),
path: `${ path }?v=${ version.id }`
} ) )
} );
} );
Expand Down
53 changes: 36 additions & 17 deletions app/[locale]/dashboard/components/file-history.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
//
// Composant de restauration des versions précédentes d'un fichier.
//

"use client";

import { formatSize } from "@/utilities/react-table";
import type { Table, Row } from "@tanstack/react-table";
import type { FileAttributes } from "@/interfaces/File";
import { Ban, Check, History, ArrowUpRight } from "lucide-react";

import { Separator } from "../../components/ui/separator";
Expand All @@ -16,40 +22,51 @@ import { AlertDialog,
AlertDialogTrigger,
AlertDialogDescription } from "../../components/ui/alert-dialog";

const tags = Array.from( { length: 9 } ).map(
( _, i, a ) => `Version du ${ a.length - i }/08/2023 - ${ i + 1 }0h${ i + 1 }0`
);

export default function FileHistory()
export default function FileHistory( {
table,
row
}: {
table: Table<FileAttributes>;
row: Row<FileAttributes>;
} )
{
// Déclaration des constantes.
const files = table.options.meta?.files ?? [];
const file = files.filter( ( value ) => value.uuid === row.id )[ 0 ];
const { versions } = file;

// Affichage du rendu HTML du composant.
return (
<ScrollArea className="h-72 rounded-md border">
{/* Aucune version précédente */}
{!versions && (
<p className="inline-block p-4 text-sm text-muted-foreground">
Aucune révision précédente n&lsquo;est disponible pour ce
fichier.
</p>
)}

{/* Liste des révisions */}
<ul className="p-4">
{tags.map( ( tag ) => (
<li key={tag} className="text-sm">
{versions?.map( ( version, index ) => (
<li key={version.id} className="text-sm">
{/* Nom de la révision */}
<h3>{tag}</h3>
<h3>Version du {version.date}</h3>

{/* Taille et différence de la révision */}
<p className="inline-block text-sm text-muted-foreground">
{Math.floor( Math.random() * 500 )} Mo
<p className="inline-block text-muted-foreground">
{formatSize( version.size )}
</p>

<p className="ml-2 inline-block text-sm font-extrabold text-primary">
<p className="ml-2 inline-block font-extrabold text-primary">
-{Math.floor( Math.random() * 100 )} Ko
</p>

<p className="ml-2 inline-block text-sm font-extrabold text-destructive">
+{Math.floor( Math.random() * 100 )} Ko
</p>

{/* Actions sur la révision */}
<div className="my-2 flex items-center gap-2">
<a
rel="noreferrer noopener"
href="https://www.google.fr/"
href={version.path}
target="_blank"
className={buttonVariants()}
>
Expand Down Expand Up @@ -104,7 +121,9 @@ export default function FileHistory()
</div>

{/* Séparateur horizontal */}
<Separator className="my-4" />
{index !== versions.length - 1 && (
<Separator className="my-4" />
)}
</li>
) )}
</ul>
Expand Down
10 changes: 6 additions & 4 deletions app/[locale]/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,23 +81,25 @@ async function getFiles(): Promise<FileAttributes[]>
// Dans le cas contraire, on récupère les informations du fichier
// avant de les retourner.
const latest = result[ 0 ];
const path = `${ process.env.__NEXT_ROUTER_BASEPATH }/d/${ latest.file.id }`;
const info = parse( latest.file.name );
const stats = await stat(
join( userStorage, object, latest.id + info.ext )
);

return {
uuid: latest.id,
uuid: latest.file.id,
name: info.name,
type: mime.getType( latest.file.name ) ?? "application/octet-stream",
size: stats.size,
date: stats.birthtime.toISOString(),
path: `${ process.env.__NEXT_ROUTER_BASEPATH }/d/${ latest.id }`,
path,
status: latest.file.status ?? "public",
versions: result.map( ( version ) => ( {
id: version.id,
size: version.size,
date: version.createdAt.toLocaleString()
size: Number( version.size ),
date: version.createdAt.toLocaleString(),
path: `${ path }?v=${ version.id }`
} ) )
} as FileAttributes;
} );
Expand Down
3 changes: 1 addition & 2 deletions app/api/file/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ export async function GET(
// On tente de récupérer l'identifiant unique de la version
// à partir des paramètres de l'URL ou via la dernière version
// du fichier fournie par la base de données.
const identifier =
request.nextUrl.searchParams.get( "version" ) ?? version.id;
const identifier = request.nextUrl.searchParams.get( "v" ) ?? version.id;
const { file } = version;
const url = new URL(
`${ process.env.__NEXT_ROUTER_BASEPATH }/files/${ file.userId }/${
Expand Down
5 changes: 4 additions & 1 deletion interfaces/File.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,12 @@ export interface FileAttributes {
id: string;

// Poids de la version en octets.
size: string;
size: number;

// Date de création de la version.
date: string;

// Chemin d'accès à la version.
path: string;
}[];
}
2 changes: 1 addition & 1 deletion middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default async function middleware( request: NextRequest )
// du fichier à partir de son identifiant.
const data = await fetch(
new URL(
`${ process.env.__NEXT_ROUTER_BASEPATH }/api/file/${ identifier }`,
`${ process.env.__NEXT_ROUTER_BASEPATH }/api/file/${ identifier }/${ request.nextUrl.search }`,
request.url
),
{ headers: request.headers }
Expand Down

0 comments on commit 874199c

Please sign in to comment.