8000 Add managed categories with up to two per item by kiran-brahma · Pull Request #2 · 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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,6 @@ webpack-stats.json
!packages/theme-kit/assets/starter/.microfeed/schemas/
!packages/theme-kit/assets/starter/.microfeed/schemas/*.json
src/worker-configuration.d.ts

# Agent runtime artifacts
.pi-subagents/
2 changes: 2 additions & 0 deletions manage-cli/lib/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ export const SNAPSHOT_TABLES = {
"themes",
"theme_drafts",
"theme_state",
"categories",
"item_categories",
],
ephemeral: [
"item_create_idempotency",
Expand Down
23 changes: 23 additions & 0 deletions migrations/0017_categories.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
-- Personal-site categories: a managed list of categories assignable to items.
-- An item can carry at most MAX_CATEGORIES_PER_ITEM (2) categories, enforced
-- in application code (see src/shared/Categories.ts and the categories service).

CREATE TABLE IF NOT EXISTS categories (
id TEXT PRIMARY KEY,
name TEXT NOT NULL COLLATE NOCASE UNIQUE,
slug TEXT NOT NULL COLLATE NOCASE UNIQUE,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS item_categories (
item_id TEXT NOT NULL,
category_id TEXT NOT NULL,
position INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (item_id, category_id)
);

CREATE INDEX IF NOT EXISTS item_categories_item_id
ON item_categories (item_id);
CREATE INDEX IF NOT EXISTS item_categories_category_id
ON item_categories (category_id);
2 changes: 2 additions & 0 deletions src/components/admin/AdminSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
PencilIcon,
PlusIcon,
SettingsIcon,
TagsIcon,
} from "lucide-react";

import {
Expand Down Expand Up @@ -36,6 +37,7 @@ const navigationIcons: Record<AdminNavItemId, typeof HomeIcon> = {
[NAV_ITEMS.ALL_ITEMS]: ListIcon,
[NAV_ITEMS.PAGES]: FileTextIcon,
[NAV_ITEMS.SITE_FILES]: FileCode2Icon,
[NAV_ITEMS.CATEGORIES]: TagsIcon,
[NAV_ITEMS.API]: Code2Icon,
[NAV_ITEMS.SETTINGS]: SettingsIcon,
};
Expand Down
237 changes: 237 additions & 0 deletions src/components/admin/categories/CategoriesApp.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
import {useState} from "react";
import {PencilIcon, PlusIcon, Trash2Icon} from "lucide-react";

import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {Label} from "@/components/ui/label";
import AdminDialog from "@/components/admin/shared/AdminDialog";
import {showToast} from "@/client/ToastUtils";
import {ADMIN_URLS} from "@/shared/StringUtils";
import {
categorySlugFromName,
type CategoryRecord,
} from "@/shared/Categories";

interface Props {
categories: CategoryRecord[];
}

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;
}

interface CategoryFormState {
name: string;
slug: string;
}

function emptyForm(): CategoryFormState {
return {name: "", slug: ""};
}

export default function CategoriesApp({categories: initialCategories}: Props) {
const [categories, setCategories] = useState(initialCategories);
const [busy, setBusy] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const [editing, setEditing] = useState<CategoryRecord | null>(null);
const [form, setForm] = useState<CategoryFormState>(emptyForm());

const openCreate = () => {
setEditing(null);
setForm(emptyForm());
setDialogOpen(true);
};

const openEdit = (category: CategoryRecord) => {
setEditing(category);
setForm({name: category.name, slug: category.slug});
setDialogOpen(true);
};

const save = async () => {
const name = form.name.trim();
if (!name) {
showToast("A category name is required.", "error");
return;
}
setBusy(true);
try {
const body = {
name,
...(form.slug.trim() ? {slug: form.slug.trim()} : {}),
};
if (editing) {
const updated = await responseJson<CategoryRecord>(await fetch(
ADMIN_URLS.ajaxCategory(editing.id),
{
body: JSON.stringify(body),
headers: {"Content-Type": "application/json"},
method: "PUT",
},
));
setCategories((current) => current.map((category) =>
category.id === updated.id ? updated : category
));
showToast("Category updated.", "success");
} else {
const created = await responseJson<CategoryRecord>(await fetch(
ADMIN_URLS.ajaxCategories(),
{
body: JSON.stringify(body),
headers: {"Content-Type": "application/json"},
method: "POST",
},
));
setCategories((current) => [...current, created]);
showToast("Category created.", "success");
}
setDialogOpen(false);
} catch (error) {
showToast(
error instanceof Error ? error.message : "The request failed.",
"error",
);
} finally {
setBusy(false);
}
};

const remove = async (category: CategoryRecord) => {
if (!window.confirm(
`Delete the category \`${category.name}\`? Items keep their content but ` +
"lose this category.",
)) {
return;
}
setBusy(true);
try {
await responseJson(await fetch(
ADMIN_URLS.ajaxCategory(category.id),
{method: "DELETE"},
));
setCategories((current) => current.filter((entry) =>
entry.id !== category.id
));
showToast("Category 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">
Categories organize your posts. Each post can carry up to two
categories.
</p>
<Button disabled={busy} type="button">
<PlusIcon aria-hidden="true" /> Add Category
</Button>
</div>
<div className="grid gap-3">
{categories.length === 0 ? (
<p className="rounded-[14px] border bg-card p-5 text-sm text-muted-foreground shadow-xs">
No categories yet. Add your first category to start organizing
posts.
</p>
) : categories.map((category) => (
<div
className="flex flex-wrap items-center justify-between gap-3 rounded-[14px] border bg-card p-4 text-card-foreground shadow-xs"
key={category.id}
>
<div>
<h2 className="font-semibold">{category.name}</h2>
<p className="text-xs text-muted-foreground">/{category.slug}</p>
</div>
<div className="flex gap-2">
<Button
disabled={busy}
=> openEdit(category)}
size="sm"
type="button"
variant="outline"
>
<PencilIcon aria-hidden="true" /> Rename
</Button>
<Button
disabled={busy}
=> void remove(category)}
size="sm"
type="button"
variant="ghost"
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
>
<Trash2Icon aria-hidden="true" /> Delete
</Button>
</div>
</div>
))}
</div>
<AdminDialog
>
open={dialogOpen}
title={editing ? "Rename category" : "Add category"}
>
<div className="grid gap-4 p-4">
<div className="grid gap-2">
<Label htmlFor="category-name">Name</Label>
<Input
autoFocus
id="category-name"
=> {
const name = event.target.value;
setForm((current) => ({
...current,
name,
...(editing || current.slug ? {} : {
slug: categorySlugFromName(name),
}),
}));
}}
placeholder="e.g. Essays"
value={form.name}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="category-slug">Slug</Label>
<Input
id="category-slug"
=> setForm((current) => ({
...current,
slug: event.target.value,
}))}
placeholder="essays"
value={form.slug}
/>
<p className="text-xs text-muted-foreground">
Used in public URLs. Leave blank to derive it from the name.
</p>
</div>
<div className="flex justify-end gap-2">
<Button
disabled={busy}
=> setDialogOpen(false)}
type="button"
variant="outline"
>
Cancel
</Button>
<Button disabled={busy} => void save()} type="button">
{editing ? "Save" : "Create"}
</Button>
</div>
</div>
</AdminDialog>
</div>
);
}
56 changes: 56 additions & 0 deletions src/components/admin/items/EditItemApp/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,21 @@ import {
} from "@/components/ui/alert-dialog";
import {queueReplacedImageUrl} from "@/client/ImageUploadUtils";
import AdminSaveAction from "@/components/admin/shared/AdminSaveAction";
import {cn} from "@/lib/utils";
import {MAX_CATEGORIES_PER_ITEM, type CategoryRecord} from "@/shared/Categories";

const SUBMIT_STATUS__START = 1;

function itemCategoryIds(item: Record<string, unknown>): string[] {
const value = item.categories;
if (!Array.isArray(value)) return [];
return value.map((entry) =>
typeof entry === "string"
? entry
: (entry as {id?: unknown})?.id
).filter((id): id is string => typeof id === "string" && id.length > 0);
}

function initItem(itemId: string) {
return ({
status: STATUSES.UNPUBLISHED,
Expand All @@ -67,6 +79,7 @@ function initItem(itemId: string) {
}

interface Props {
categories: CategoryRecord[];
feedContent: FeedContent;
itemId?: string;
onboardingResult: OnboardingResult;
Expand Down Expand Up @@ -412,6 +425,49 @@ export default class EditItemApp extends React.Component<Props, any> {
/>
</div>
</div>
<div className="rounded-[14px] border bg-card p-5 text-card-foreground shadow-xs">
<div className="mb-2 text-sm font-semibold text-foreground">Categories</div>
<p className="mb-4 text-xs text-muted-foreground">
Assign up to {MAX_CATEGORIES_PER_ITEM} categories to this post.
</p>
{this.props.categories?.length === 0 ? (
<p className="text-sm text-muted-foreground">
No categories yet. Add categories in the Categories page first.
</p>
) : (
<div className="flex flex-wrap gap-2">
{(this.props.categories ?? []).map((category) => {
const selected = itemCategoryIds(item).includes(category.id);
const atLimit = itemCategoryIds(item).length >= MAX_CATEGORIES_PER_ITEM;
const disabled = !selected && atLimit;
return (
<button
aria-pressed={selected}
className={cn(
"rounded-full border px-3 py-1.5 text-sm font-medium transition",
selected
? "border-primary bg-primary/10 text-primary"
: "border-border bg-card text-foreground hover:border-primary/40 hover:bg-accent/30",
disabled && "cursor-not-allowed opacity-45",
)}
disabled={disabled}
key={category.id}
=> {
const current = itemCategoryIds(item);
const next = selected
? current.filter((id) => id !== category.id)
: [...current, category.id];
this.onUpdateItemMeta({categories: next});
}}
type="button"
>
{category.name}
</button>
);
})}
</div>
)}
</div>
<div className="rounded-[14px] border bg-card p-5 text-card-foreground shadow-xs">
<details>
<summary className="m-page-summary">Podcast-specific fields</summary>
Expand Down
5 changes: 5 additions & 0 deletions src/pages/[adminPath]/ajax/categories/[categoryId]/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export {
deleteAdminCategory as DELETE,
getAdminCategory as GET,
updateAdminCategory as PUT,
} from "@/server/admin/category-handlers";
4 changes: 4 additions & 0 deletions src/pages/[adminPath]/ajax/categories/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export {
createAdminCategory as POST,
listAdminCategories as GET,
} from "@/server/admin/category-handlers";
Loading
0