8000 Add global media library with reuse and AVIF conversion by kiran-brahma · Pull Request #5 · kiran-brahma/microfeed · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions manage-cli/lib/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export const SNAPSHOT_TABLES = {
"series",
"item_series",
"contact_messages",
"media_library",
],
ephemeral: [
"item_create_idempotency",
Expand Down
20 changes: 20 additions & 0 deletions migrations/0020_media_library.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
-- Personal-site media library: a global registry of uploaded media so the
-- owner can upload once and reuse the same image across posts. Records are
-- created when a signed upload completes (see src/pages/media-upload/[...key].ts)
-- and are removed when the owner deletes the entry from the Admin library.

CREATE TABLE IF NOT EXISTS media_library (
id TEXT PRIMARY KEY,
object_key TEXT NOT NULL UNIQUE,
url TEXT NOT NULL,
filename TEXT NOT NULL,
content_type TEXT,
size_bytes INTEGER,
width INTEGER,
height INTEGER,
format TEXT,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS media_library_created_at
ON media_library (created_at);
2 changes: 2 additions & 0 deletions src/components/admin/AdminSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
TagsIcon,
LayersIcon,
MailIcon,
ImagesIcon,
} from "lucide-react";

import {
Expand Down Expand Up @@ -42,6 +43,7 @@ const navigationIcons: Record<AdminNavItemId, typeof HomeIcon> = {
[NAV_ITEMS.CATEGORIES]: TagsIcon,
[NAV_ITEMS.SERIES]: LayersIcon,
[NAV_ITEMS.CONTACT_MESSAGES]: MailIcon,
[NAV_ITEMS.MEDIA_LIBRARY]: ImagesIcon,
[NAV_ITEMS.API]: Code2Icon,
[NAV_ITEMS.SETTINGS]: SettingsIcon,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,15 @@ import {
} from "@/shared/Constants";
import AdminRadioGroup from "@/components/admin/shared/AdminRadioGroup";
import AdminInput from "@/components/admin/shared/AdminInput";
import AdminDialog from "@/components/admin/shared/AdminDialog";
import FileUploader from "@/components/admin/shared/AdminFileUploader";
import {CloudUploadIcon} from "lucide-react";
import {CloudUploadIcon, ImagesIcon} from "lucide-react";
import {getPublicBaseUrl} from "@/client/ClientUrlUtils";
import {showToast} from "@/client/ToastUtils";
import {getMediaFileFromUrl} from "@/shared/MediaFileUtils";
import type {MediaLibraryRecord} from "@/shared/MediaLibrary";
import MediaStorageUnavailableDialog from "@/components/admin/shared/MediaStorageUnavailableDialog";
import {Button} from "@/components/ui/button";

const UPLOAD_STATUS__START = 1;

Expand Down Expand Up @@ -191,6 +194,9 @@ export default class MediaManager extends React.Component<any, any> {
uploadStatus: null,
progressText: '0.00%',
showMediaStorageUnavailable: false,
showLibrary: false,
libraryEntries: [],
libraryLoading: false,
};
}

Expand Down Expand Up @@ -256,11 +262,47 @@ export default class MediaManager extends React.Component<any, any> {
this.setState({showMediaStorageUnavailable: true});
}

async openLibrary() {
this.setState({showLibrary: true, libraryLoading: true});
try {
const response = await fetch(ADMIN_URLS.ajaxMediaLibrary(), {
headers: {accept: "application/json"},
});
const body = await response.json().catch(() => ({})) as {
items?: MediaLibraryRecord[];
};
this.setState({
libraryEntries: Array.isArray(body.items) ? body.items : [],
libraryLoading: false,
});
} catch {
this.setState({libraryLoading: false});
showToast("Failed to load the media library.", "error");
}
}

pickFromLibrary(entry: MediaLibraryRecord) {
this.setState({
showLibrary: false,
url: entry.object_key,
contentType: entry.content_type || 'image/avif',
sizeByte: entry.size_bytes || 0,
}, () => {
this.props.onMediaFileUpdated({
url: entry.object_key,
sizeByte: entry.size_bytes || 0,
contentType: entry.content_type || 'image/avif',
category: ENCLOSURE_CATEGORIES.IMAGE,
}, {immediate: true});
});
}

render() {
const {
category, url, contentType, sizeByte, durationSecond,
uploadStatus, progressText, publicBucketUrl,
showMediaStorageUnavailable,
showMediaStorageUnavailable, showLibrary, libraryEntries,
libraryLoading,
} = this.state;
const {label, labelComponent} = this.props;
const mediaStorageReady = this.props.mediaStorageReady !== false;
Expand Down Expand Up @@ -361,6 +403,19 @@ export default class MediaManager extends React.Component<any, any> {
>
>
/>}
{category === ENCLOSURE_CATEGORIES.IMAGE && (
<div className="mt-3">
<Button
disabled={uploading}
=> void this.openLibrary()}
size="sm"
type="button"
variant="outline"
>
<ImagesIcon aria-hidden="true" /> Choose from library
</Button>
</div>
)}
</div>
<MediaStorageUnavailableDialog
dashboardUrl={this.props.mediaStorage?.dashboardUrl}
Expand All @@ -370,6 +425,46 @@ export default class MediaManager extends React.Component<any, any> {
open={showMediaStorageUnavailable}
state={this.props.mediaStorage?.mediaStorageState}
/>
<AdminDialog
title="Choose from media library"
open={showLibrary}
=> this.setState({showLibrary: open})}
>
<div className="p-4">
{libraryLoading ? (
<p className="text-sm text-muted-foreground">Loading media library...</p>
) : libraryEntries.length === 0 ? (
<p className="text-sm text-muted-foreground">
No media yet. Upload an image first and it will appear here.
</p>
) : (
<div className="grid max-h-96 grid-cols-3 gap-3 overflow-y-auto">
{libraryEntries.map((entry: MediaLibraryRecord) => (
<button
className="group relative aspect-square w-full overflow-hidden rounded-md border border-border bg-muted outline-none transition hover:border-primary focus-visible:ring-2 focus-visible:ring-primary"
key={entry.id}
=> this.pickFromLibrary(entry)}
title={entry.filename}
type="button"
>
{entry.content_type?.startsWith("image/") ? (
<img
alt={entry.filename}
className="h-full w-full object-cover"
loading="lazy"
src={urlJoinWithRelative(publicBucketUrl, entry.url)}
/>
) : (
<div className="flex h-full w-full items-center justify-center text-muted-foreground">
<ImagesIcon aria-hidden="true" className="size-6" />
</div>
)}
</button>
))}
</div>
)}
</div>
</AdminDialog>
</div>);
}
}
120 changes: 120 additions & 0 deletions src/components/admin/media-library/MediaLibraryApp.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import {useState} from "react";
import {ImageIcon, Trash2Icon} from "lucide-react";

import {Button} from "@/components/ui/button";
import {showToast} from "@/client/ToastUtils";
import {ADMIN_URLS, humanFileSize, resolvePublicBucketUrl, urlJoinWithRelative} from "@/shared/StringUtils";
import type {MediaLibraryRecord} from "@/shared/MediaLibrary";

interface Props {
entries: MediaLibraryRecord[];
publicBucketUrl?: string;
}

async function responseJson<T>(response: Response): Promise<T> {
const body = await response.json().catch(() => ({})) as T & {error?: string};
if (!response.ok) {
throw new Error(body.error ?? "The request failed.");
}
return body;
}

function absoluteUrl(url: string, publicBucketUrl: string): string {
return urlJoinWithRelative(publicBucketUrl, url) ?? url;
}

export default function MediaLibraryApp({entries: initialEntries, publicBucketUrl: initialPublicBucketUrl}: Props) {
const [entries, setEntries] = useState(initialEntries);
const [busy, setBusy] = useState(false);
const publicBucketUrl = initialPublicBucketUrl ||
resolvePublicBucketUrl("/media/", window.location.hostname);

const remove = async (entry: MediaLibraryRecord) => {
if (!window.confirm(
`Delete \`${entry.filename}\` from the media library? This permanently ` +
"removes the uploaded file. Posts that already use this image keep " +
"their current copy but the file will stop loading.",
)) {
return;
}
setBusy(true);
try {
await responseJson(await fetch(
ADMIN_URLS.ajaxMediaLibraryEntry(entry.id),
{method: "DELETE"},
));
setEntries((current) => current.filter((item) => item.id !== entry.id));
showToast("Media deleted.", "success");
} catch (error) {
showToast(
error instanceof Error ? error.message : "The request failed.",
"error",
);
} finally {
setBusy(false);
}
};

return (
<div className="grid gap-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<p className="text-sm text-muted-foreground">
Every image you upload lands here. Pick one from the library when
adding a post cover or inline image so you never re-upload the same
file.
</p>
</div>
{entries.length === 0 ? (
<p className="rounded-[14px] border bg-card p-5 text-sm text-muted-foreground shadow-xs">
No media yet. Upload an image from an item editor and it will appear
here.
</p>
) : (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
{entries.map((entry) => (
<div
className="group overflow-hidden rounded-[14px] border bg-card text-card-foreground shadow-xs"
key={entry.id}
>
<div className="relative aspect-square w-full overflow-hidden bg-muted">
{entry.content_type?.startsWith("image/") ? (
<img
alt={entry.filename}
className="h-full w-full object-cover"
loading="lazy"
src={absoluteUrl(entry.url, publicBucketUrl)}
/>
) : (
<div className="flex h-full w-full items-center justify-center text-muted-foreground">
<ImageIcon aria-hidden="true" className="size-8" />
</div>
)}
</div>
<div className="p-3">
<p className="truncate text-sm font-medium" title={entry.filename}>
{entry.filename}
</p>
<p className="mt-1 text-xs text-muted-foreground">
{entry.format?.toUpperCase() ?? entry.content_type ?? "file"}
{entry.size_bytes !== null
? ` · ${humanFileSize(entry.size_bytes)}`
: ""}
</p>
<Button
className="mt-2 w-full text-destructive hover:bg-destructive/10 hover:text-destructive"
disabled={busy}
=> void remove(entry)}
size="sm"
type="button"
variant="ghost"
>
<Trash2Icon aria-hidden="true" /> Delete
</Button>
</div>
</div>
))}
</div>
)}
</div>
);
}
Loading
0