migration of comments

This commit is contained in:
Michael Freno
2025-12-17 22:47:19 -05:00
parent a092c57d36
commit 1bc57c61eb
37 changed files with 3022 additions and 442 deletions

View File

@@ -3,85 +3,119 @@ import { useParams, A } from "@solidjs/router";
import { Title } from "@solidjs/meta";
import { createAsync } from "@solidjs/router";
import { cache } from "@solidjs/router";
import { ConnectionFactory } from "~/server/utils";
import {
ConnectionFactory,
getUserID,
getPrivilegeLevel
} from "~/server/utils";
import { getRequestEvent } from "solid-js/web";
import { HttpStatusCode } from "@solidjs/start";
import SessionDependantLike from "~/components/blog/SessionDependantLike";
import CommentIcon from "~/components/icons/CommentIcon";
import CommentSectionWrapper from "~/components/blog/CommentSectionWrapper";
import type { Comment, CommentReaction, UserPublicData } from "~/types/comment";
// Server function to fetch post by title
const getPostByTitle = cache(async (title: string, privilegeLevel: string) => {
const getPostByTitle = cache(async (title: string) => {
"use server";
const event = getRequestEvent()!;
const privilegeLevel = await getPrivilegeLevel(event.nativeEvent);
const userID = await getUserID(event.nativeEvent);
const conn = ConnectionFactory();
let query = "SELECT * FROM Post WHERE title = ?";
if (privilegeLevel !== "admin") {
query += ` AND published = TRUE`;
}
const postResults = await conn.execute({
sql: query,
args: [decodeURIComponent(title)],
args: [decodeURIComponent(title)]
});
const post = postResults.rows[0] as any;
if (!post) {
// Check if post exists but is unpublished
const existQuery = "SELECT id FROM Post WHERE title = ?";
const existRes = await conn.execute({
sql: existQuery,
args: [decodeURIComponent(title)],
args: [decodeURIComponent(title)]
});
if (existRes.rows[0]) {
return { post: null, exists: true, comments: [], likes: [], tags: [], userCommentMap: new Map() };
return {
post: null,
exists: true,
comments: [],
likes: [],
tags: [],
userCommentArray: [],
reactionArray: [],
privilegeLevel: "anonymous" as const,
userID: null
};
}
return { post: null, exists: false, comments: [], likes: [], tags: [], userCommentMap: new Map() };
return {
post: null,
exists: false,
comments: [],
likes: [],
tags: [],
userCommentArray: [],
reactionArray: [],
privilegeLevel: "anonymous" as const,
userID: null
};
}
// Fetch comments
const commentQuery = "SELECT * FROM Comment WHERE post_id = ?";
const comments = (await conn.execute({ sql: commentQuery, args: [post.id] })).rows;
const comments = (await conn.execute({ sql: commentQuery, args: [post.id] }))
.rows;
// Fetch likes
const likeQuery = "SELECT * FROM PostLike WHERE post_id = ?";
const likes = (await conn.execute({ sql: likeQuery, args: [post.id] })).rows;
// Fetch tags
const tagQuery = "SELECT * FROM Tag WHERE post_id = ?";
const tags = (await conn.execute({ sql: tagQuery, args: [post.id] })).rows;
// Build commenter map
const commenterToCommentIDMap = new Map<string, number[]>();
comments.forEach((comment: any) => {
const prev = commenterToCommentIDMap.get(comment.commenter_id) || [];
commenterToCommentIDMap.set(comment.commenter_id, [...prev, comment.id]);
});
const commenterQuery = "SELECT email, display_name, image FROM User WHERE id = ?";
const commentIDToCommenterMap = new Map();
const commenterQuery =
"SELECT email, display_name, image FROM User WHERE id = ?";
// Convert to serializable array format
const userCommentArray: Array<[UserPublicData, number[]]> = [];
for (const [key, value] of commenterToCommentIDMap.entries()) {
const res = await conn.execute({ sql: commenterQuery, args: [key] });
const user = res.rows[0];
if (user) {
commentIDToCommenterMap.set(user, value);
userCommentArray.push([user as UserPublicData, value]);
}
}
// Get reaction map
const reactionMap = new Map();
// Get reaction map as serializable array
const reactionArray: Array<[number, CommentReaction[]]> = [];
for (const comment of comments) {
const reactionQuery = "SELECT * FROM CommentReaction WHERE comment_id = ?";
const res = await conn.execute({
sql: reactionQuery,
args: [(comment as any).id],
args: [(comment as any).id]
});
reactionMap.set((comment as any).id, res.rows);
reactionArray.push([(comment as any).id, res.rows as CommentReaction[]]);
}
return {
post,
exists: true,
@@ -89,20 +123,18 @@ const getPostByTitle = cache(async (title: string, privilegeLevel: string) => {
likes,
tags,
topLevelComments: comments.filter((c: any) => c.parent_comment_id == null),
userCommentMap: commentIDToCommenterMap,
reactionMap,
userCommentArray,
reactionArray,
privilegeLevel,
userID
};
}, "post-by-title");
export default function PostPage() {
const params = useParams();
// TODO: Get actual privilege level and user ID from session/auth
const privilegeLevel = "anonymous";
const userID = null;
const data = createAsync(() => getPostByTitle(params.title, privilegeLevel));
const data = createAsync(() => getPostByTitle(params.title));
const hasCodeBlock = (str: string): boolean => {
return str.includes("<code") && str.includes("</code>");
};
@@ -117,154 +149,165 @@ export default function PostPage() {
}
>
<Show
when={data()}
when={data()?.post}
fallback={
<div class="w-full pt-[30vh]">
<HttpStatusCode code={404} />
<div class="text-center text-2xl">Post not found</div>
</div>
}
>
{(postData) => (
<Show
when={postData().post}
when={data()?.exists}
fallback={
<Show
when={postData().exists}
fallback={
<div class="w-full pt-[30vh]">
<HttpStatusCode code={404} />
<div class="text-center text-2xl">Post not found</div>
</div>
}
>
<div class="w-full pt-[30vh]">
<div class="text-center text-2xl">
That post is in the works! Come back soon!
</div>
<div class="flex justify-center">
<A
href="/blog"
class="mt-4 rounded border border-orange-500 bg-orange-400 px-4 py-2 text-white shadow-md transition-all duration-300 ease-in-out hover:bg-orange-500 active:scale-90 dark:border-orange-700 dark:bg-orange-700 dark:hover:bg-orange-800"
>
Back to Posts
</A>
</div>
</div>
</Show>
<div class="w-full pt-[30vh]">
<HttpStatusCode code={404} />
<div class="text-center text-2xl">Post not found</div>
</div>
}
>
{(post) => {
const p = post().post;
return (
<>
<Title>{p.title.replaceAll("_", " ")} | Michael Freno</Title>
<div class="select-none overflow-x-hidden">
<div class="z-30">
<div class="page-fade-in z-20 mx-auto h-80 sm:h-96 md:h-[50vh]">
<div class="image-overlay fixed h-80 w-full brightness-75 sm:h-96 md:h-[50vh]">
<img
src={p.banner_photo || "/blueprint.jpg"}
alt="post-cover"
class="h-80 w-full object-cover sm:h-96 md:h-[50vh]"
/>
</div>
<div
class="text-shadow fixed top-36 z-10 w-full select-text text-center tracking-widest text-white brightness-150 sm:top-44 md:top-[20vh]"
style={{ "pointer-events": "none" }}
>
<div class="z-10 text-3xl font-light tracking-widest">
{p.title.replaceAll("_", " ")}
<div class="py-8 text-xl font-light tracking-widest">
{p.subtitle}
</div>
</div>
</div>
</div>
<div class="w-full pt-[30vh]">
<div class="text-center text-2xl">
That post is in the works! Come back soon!
</div>
<div class="flex justify-center">
<A
href="/blog"
class="border-peach bg-peach mt-4 rounded border px-4 py-2 text-base shadow-md transition-all duration-300 ease-in-out hover:brightness-125 active:scale-90"
>
Back to Posts
</A>
</div>
</div>
</Show>
}
>
{(p) => {
const postData = data()!;
// Convert arrays back to Maps for component
const userCommentMap = new Map<UserPublicData, number[]>(
postData.userCommentArray || []
);
const reactionMap = new Map<number, CommentReaction[]>(
postData.reactionArray || []
);
return (
<>
<Title>{p().title.replaceAll("_", " ")} | Michael Freno</Title>
<div class="overflow-x-hidden select-none">
<div class="z-30">
<div class="page-fade-in z-20 mx-auto h-80 sm:h-96 md:h-[50vh]">
<div class="image-overlay fixed h-80 w-full brightness-75 sm:h-96 md:h-[50vh]">
<img
src={p().banner_photo || "/blueprint.jpg"}
alt="post-cover"
class="h-80 w-full object-cover sm:h-96 md:h-[50vh]"
/>
</div>
<div class="relative z-40 bg-zinc-100 pb-24 dark:bg-zinc-800">
<div class="top-4 flex w-full flex-col justify-center md:absolute md:flex-row md:justify-between">
<div class="">
<div class="flex justify-center italic md:justify-start md:pl-24">
<div>
Written {new Date(p.date).toDateString()}
<br />
By Michael Freno
</div>
</div>
<div class="flex max-w-[420px] flex-wrap justify-center italic md:justify-start md:pl-24">
<For each={postData().tags as any[]}>
{(tag) => (
<div class="group relative m-1 h-fit w-fit rounded-xl bg-purple-600 px-2 py-1 text-sm">
<div class="text-white">{tag.value}</div>
</div>
)}
</For>
</div>
</div>
<div class="flex flex-row justify-center pt-4 md:pr-8 md:pt-0">
<a href="#comments" class="mx-2">
<div class="tooltip flex flex-col">
<div class="mx-auto">
<CommentIcon strokeWidth={1} height={32} width={32} />
</div>
<div class="my-auto pl-2 pt-0.5 text-sm text-black dark:text-white">
{postData().comments.length}{" "}
{postData().comments.length === 1 ? "Comment" : "Comments"}
</div>
</div>
</a>
<div class="mx-2">
<SessionDependantLike
currentUserID={userID}
privilegeLevel={privilegeLevel}
likes={postData().likes as any[]}
type={p.category === "project" ? "project" : "blog"}
projectID={p.id}
/>
</div>
</div>
</div>
{/* Post body */}
<div class="mx-auto max-w-4xl px-4 pt-32 md:pt-40">
<div class="prose dark:prose-invert max-w-none" innerHTML={p.body} />
</div>
<Show when={privilegeLevel === "admin"}>
<div class="flex justify-center">
<A
class="z-100 h-fit rounded border border-blue-500 bg-blue-400 px-4 py-2 text-white shadow-md transition-all duration-300 ease-in-out hover:bg-blue-500 active:scale-90 dark:border-blue-700 dark:bg-blue-700 dark:hover:bg-blue-800"
href={`/blog/edit/${p.id}`}
>
Edit
</A>
</div>
</Show>
{/* Comments section */}
<div id="comments" class="mx-4 pb-12 pt-12 md:mx-8 lg:mx-12">
<div class="mb-8 text-center text-2xl font-semibold">Comments</div>
<div class="mx-auto max-w-2xl rounded-lg border border-zinc-300 bg-zinc-50 p-6 text-center dark:border-zinc-700 dark:bg-zinc-900">
<p class="mb-2 text-lg text-zinc-700 dark:text-zinc-300">
Comments coming soon!
</p>
<p class="text-sm text-zinc-500 dark:text-zinc-400">
We're working on implementing a comment system for this blog.
</p>
<div
class="text-shadow fixed top-36 z-10 w-full text-center tracking-widest text-white brightness-150 select-text sm:top-44 md:top-[20vh]"
style={{ "pointer-events": "none" }}
>
<div class="z-10 text-3xl font-light tracking-widest">
{p().title.replaceAll("_", " ")}
<div class="py-8 text-xl font-light tracking-widest">
{p().subtitle}
</div>
</div>
</div>
</div>
</>
);
}}
</Show>
)}
</div>
<div class="bg-surface0 relative z-40 pb-24">
<div class="top-4 flex w-full flex-col justify-center md:absolute md:flex-row md:justify-between">
<div class="">
<div class="flex justify-center italic md:justify-start md:pl-24">
<div>
Written {new Date(p().date).toDateString()}
<br />
By Michael Freno
</div>
</div>
<div class="flex max-w-[420px] flex-wrap justify-center italic md:justify-start md:pl-24">
<For each={postData.tags as any[]}>
{(tag) => (
<div class="group relative m-1 h-fit w-fit rounded-xl bg-purple-600 px-2 py-1 text-sm">
<div class="text-white">{tag.value}</div>
</div>
)}
</For>
</div>
</div>
<div class="flex flex-row justify-center pt-4 md:pt-0 md:pr-8">
<a href="#comments" class="mx-2">
<div class="tooltip flex flex-col">
<div class="mx-auto">
<CommentIcon
strokeWidth={1}
height={32}
width={32}
/>
</div>
<div class="text-text my-auto pt-0.5 pl-2 text-sm">
{postData.comments.length}{" "}
{postData.comments.length === 1
? "Comment"
: "Comments"}
</div>
</div>
</a>
<div class="mx-2">
<SessionDependantLike
currentUserID={postData.userID}
privilegeLevel={postData.privilegeLevel}
likes={postData.likes as any[]}
type={
p().category === "project" ? "project" : "blog"
}
projectID={p().id}
/>
</div>
</div>
</div>
{/* Post body */}
<div class="mx-auto max-w-4xl px-4 pt-32 md:pt-40">
<div class="prose max-w-none" innerHTML={p().body} />
</div>
<Show when={postData.privilegeLevel === "admin"}>
<div class="flex justify-center">
<A
class="border-blue bg-blue z-100 h-fit rounded border px-4 py-2 text-base shadow-md transition-all duration-300 ease-in-out hover:brightness-125 active:scale-90"
href={`/blog/edit/${p().id}`}
>
Edit
</A>
</div>
</Show>
{/* Comments section */}
<div
id="comments"
class="mx-4 pt-12 pb-12 md:mx-8 lg:mx-12"
>
<CommentSectionWrapper
privilegeLevel={postData.privilegeLevel}
allComments={postData.comments as Comment[]}
topLevelComments={
postData.topLevelComments as Comment[]
}
id={p().id}
type="blog"
reactionMap={reactionMap}
currentUserID={postData.userID || ""}
userCommentMap={userCommentMap}
/>
</div>
</div>
</div>
</>
);
}}
</Show>
</Suspense>
</>

View File

@@ -6,13 +6,14 @@ import { api } from "~/lib/api";
export default function CreatePost() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
// TODO: Get actual privilege level from session/auth
const privilegeLevel = "anonymous";
const userID = null;
const category = () => searchParams.category === "project" ? "project" : "blog";
const category = () =>
searchParams.category === "project" ? "project" : "blog";
const [title, setTitle] = createSignal("");
const [subtitle, setSubtitle] = createSignal("");
const [body, setBody] = createSignal("");
@@ -24,15 +25,15 @@ export default function CreatePost() {
const handleSubmit = async (e: Event) => {
e.preventDefault();
if (!userID) {
setError("You must be logged in to create a post");
return;
}
setLoading(true);
setError("");
try {
const result = await api.database.createPost.mutate({
category: category(),
@@ -42,9 +43,9 @@ export default function CreatePost() {
banner_photo: bannerPhoto() || null,
published: published(),
tags: tags().length > 0 ? tags() : null,
author_id: userID,
author_id: userID
});
if (result.data) {
// Redirect to the new post
navigate(`/blog/${encodeURIComponent(title())}`);
@@ -59,29 +60,32 @@ export default function CreatePost() {
return (
<>
<Title>Create {category() === "project" ? "Project" : "Blog Post"} | Michael Freno</Title>
<Title>
Create {category() === "project" ? "Project" : "Blog Post"} | Michael
Freno
</Title>
<Show
when={privilegeLevel === "admin"}
fallback={
<div class="w-full pt-[30vh] text-center">
<div class="text-2xl">Unauthorized</div>
<div class="text-gray-600 dark:text-gray-400 mt-4">
<div class="text-text text-2xl">Unauthorized</div>
<div class="text-subtext0 mt-4">
You must be an admin to create posts.
</div>
</div>
}
>
<div class="min-h-screen bg-white dark:bg-zinc-900 py-12 px-4">
<div class="max-w-4xl mx-auto">
<h1 class="text-4xl font-bold text-center mb-8">
<div class="bg-base min-h-screen px-4 py-12">
<div class="mx-auto max-w-4xl">
<h1 class="mb-8 text-center text-4xl font-bold">
Create {category() === "project" ? "Project" : "Blog Post"}
</h1>
<form onSubmit={handleSubmit} class="space-y-6">
{/* Title */}
<div>
<label for="title" class="block text-sm font-medium mb-2">
<label for="title" class="mb-2 block text-sm font-medium">
Title *
</label>
<input
@@ -90,14 +94,14 @@ export default function CreatePost() {
required
value={title()}
onInput={(e) => setTitle(e.currentTarget.value)}
class="w-full px-4 py-2 border border-gray-300 rounded-md dark:bg-zinc-800 dark:border-zinc-700"
class="border-surface2 bg-surface0 w-full rounded-md border px-4 py-2"
placeholder="Enter post title"
/>
</div>
{/* Subtitle */}
<div>
<label for="subtitle" class="block text-sm font-medium mb-2">
<label for="subtitle" class="mb-2 block text-sm font-medium">
Subtitle
</label>
<input
@@ -105,14 +109,14 @@ export default function CreatePost() {
type="text"
value={subtitle()}
onInput={(e) => setSubtitle(e.currentTarget.value)}
class="w-full px-4 py-2 border border-gray-300 rounded-md dark:bg-zinc-800 dark:border-zinc-700"
class="border-surface2 bg-surface0 w-full rounded-md border px-4 py-2"
placeholder="Enter post subtitle"
/>
</div>
{/* Body */}
<div>
<label for="body" class="block text-sm font-medium mb-2">
<label for="body" class="mb-2 block text-sm font-medium">
Body (HTML)
</label>
<textarea
@@ -120,14 +124,14 @@ export default function CreatePost() {
rows={15}
value={body()}
onInput={(e) => setBody(e.currentTarget.value)}
class="w-full px-4 py-2 border border-gray-300 rounded-md dark:bg-zinc-800 dark:border-zinc-700 font-mono text-sm"
class="w-full rounded-md border border-surface2 bg-surface0 px-4 py-2 font-mono text-sm"
placeholder="Enter post content (HTML)"
/>
</div>
{/* Banner Photo URL */}
<div>
<label for="banner" class="block text-sm font-medium mb-2">
<label for="banner" class="mb-2 block text-sm font-medium">
Banner Photo URL
</label>
<input
@@ -135,26 +139,33 @@ export default function CreatePost() {
type="text"
value={bannerPhoto()}
onInput={(e) => setBannerPhoto(e.currentTarget.value)}
class="w-full px-4 py-2 border border-gray-300 rounded-md dark:bg-zinc-800 dark:border-zinc-700"
class="border-surface2 bg-surface0 w-full rounded-md border px-4 py-2"
placeholder="Enter banner photo URL"
/>
</div>
{/* Tags */}
<div>
<label for="tags" class="block text-sm font-medium mb-2">
<label for="tags" class="mb-2 block text-sm font-medium">
Tags (comma-separated)
</label>
<input
id="tags"
type="text"
value={tags().join(", ")}
onInput={(e) => setTags(e.currentTarget.value.split(",").map(t => t.trim()).filter(Boolean))}
class="w-full px-4 py-2 border border-gray-300 rounded-md dark:bg-zinc-800 dark:border-zinc-700"
onInput={(e) =>
setTags(
e.currentTarget.value
.split(",")
.map((t) => t.trim())
.filter(Boolean)
)
}
class="border-surface2 bg-surface0 w-full rounded-md border px-4 py-2"
placeholder="tag1, tag2, tag3"
/>
</div>
{/* Published */}
<div class="flex items-center gap-2">
<input
@@ -168,30 +179,30 @@ export default function CreatePost() {
Publish immediately
</label>
</div>
{/* Error message */}
<Show when={error()}>
<div class="text-red-500 text-sm">{error()}</div>
<div class="text-red text-sm">{error()}</div>
</Show>
{/* Submit button */}
<div class="flex gap-4">
<button
type="submit"
disabled={loading()}
class={`flex-1 px-6 py-3 rounded-md text-white transition-all ${
class={`flex-1 rounded-md px-6 py-3 text-base transition-all ${
loading()
? "bg-gray-400 cursor-not-allowed"
: "bg-blue-500 hover:bg-blue-600 active:scale-95"
? "bg-blue cursor-not-allowed brightness-50"
: "bg-blue hover:brightness-125 active:scale-95"
}`}
>
{loading() ? "Creating..." : "Create Post"}
</button>
<button
type="button"
onClick={() => navigate("/blog")}
class="px-6 py-3 rounded-md border border-gray-300 hover:bg-gray-100 dark:hover:bg-zinc-800 transition-all"
class="border-surface2 rounded-md border px-6 py-3 transition-all hover:brightness-125"
>
Cancel
</button>

View File

@@ -9,36 +9,36 @@ import { ConnectionFactory } from "~/server/utils";
// Server function to fetch post for editing
const getPostForEdit = cache(async (id: string) => {
"use server";
const conn = ConnectionFactory();
const query = `SELECT * FROM Post WHERE id = ?`;
const results = await conn.execute({
sql: query,
args: [id],
args: [id]
});
const tagQuery = `SELECT * FROM Tag WHERE post_id = ?`;
const tagRes = await conn.execute({
sql: tagQuery,
args: [id],
args: [id]
});
const post = results.rows[0];
const tags = tagRes.rows;
return { post, tags };
}, "post-for-edit");
export default function EditPost() {
const params = useParams();
const navigate = useNavigate();
// TODO: Get actual privilege level from session/auth
const privilegeLevel = "anonymous";
const userID = null;
const data = createAsync(() => getPostForEdit(params.id));
const [title, setTitle] = createSignal("");
const [subtitle, setSubtitle] = createSignal("");
const [body, setBody] = createSignal("");
@@ -47,7 +47,7 @@ export default function EditPost() {
const [tags, setTags] = createSignal<string[]>([]);
const [loading, setLoading] = createSignal(false);
const [error, setError] = createSignal("");
// Populate form when data loads
createEffect(() => {
const postData = data();
@@ -58,9 +58,9 @@ export default function EditPost() {
setBody(p.body || "");
setBannerPhoto(p.banner_photo || "");
setPublished(p.published || false);
if (postData.tags) {
const tagValues = (postData.tags as any[]).map(t => t.value);
const tagValues = (postData.tags as any[]).map((t) => t.value);
setTags(tagValues);
}
}
@@ -68,15 +68,15 @@ export default function EditPost() {
const handleSubmit = async (e: Event) => {
e.preventDefault();
if (!userID) {
setError("You must be logged in to edit posts");
return;
}
setLoading(true);
setError("");
try {
await api.database.updatePost.mutate({
id: parseInt(params.id),
@@ -86,9 +86,9 @@ export default function EditPost() {
banner_photo: bannerPhoto() || null,
published: published(),
tags: tags().length > 0 ? tags() : null,
author_id: userID,
author_id: userID
});
// Redirect to the post
navigate(`/blog/${encodeURIComponent(title())}`);
} catch (err) {
@@ -102,13 +102,13 @@ export default function EditPost() {
return (
<>
<Title>Edit Post | Michael Freno</Title>
<Show
when={privilegeLevel === "admin"}
fallback={
<div class="w-full pt-[30vh] text-center">
<div class="text-2xl">Unauthorized</div>
<div class="text-gray-600 dark:text-gray-400 mt-4">
<div class="text-subtext0 mt-4">
You must be an admin to edit posts.
</div>
</div>
@@ -122,14 +122,14 @@ export default function EditPost() {
</div>
}
>
<div class="min-h-screen bg-white dark:bg-zinc-900 py-12 px-4">
<div class="max-w-4xl mx-auto">
<h1 class="text-4xl font-bold text-center mb-8">Edit Post</h1>
<div class="bg-base min-h-screen px-4 py-12">
<div class="mx-auto max-w-4xl">
<h1 class="mb-8 text-center text-4xl font-bold">Edit Post</h1>
<form onSubmit={handleSubmit} class="space-y-6">
{/* Title */}
<div>
<label for="title" class="block text-sm font-medium mb-2">
<label for="title" class="mb-2 block text-sm font-medium">
Title *
</label>
<input
@@ -138,14 +138,14 @@ export default function EditPost() {
required
value={title()}
onInput={(e) => setTitle(e.currentTarget.value)}
class="w-full px-4 py-2 border border-gray-300 rounded-md dark:bg-zinc-800 dark:border-zinc-700"
class="w-full rounded-md border border-surface2 bg-surface0 px-4 py-2"
placeholder="Enter post title"
/>
</div>
{/* Subtitle */}
<div>
<label for="subtitle" class="block text-sm font-medium mb-2">
<label for="subtitle" class="mb-2 block text-sm font-medium">
Subtitle
</label>
<input
@@ -153,14 +153,14 @@ export default function EditPost() {
type="text"
value={subtitle()}
onInput={(e) => setSubtitle(e.currentTarget.value)}
class="w-full px-4 py-2 border border-gray-300 rounded-md dark:bg-zinc-800 dark:border-zinc-700"
class="w-full rounded-md border border-surface2 bg-surface0 px-4 py-2"
placeholder="Enter post subtitle"
/>
</div>
{/* Body */}
<div>
<label for="body" class="block text-sm font-medium mb-2">
<label for="body" class="mb-2 block text-sm font-medium">
Body (HTML)
</label>
<textarea
@@ -168,14 +168,14 @@ export default function EditPost() {
rows={15}
value={body()}
onInput={(e) => setBody(e.currentTarget.value)}
class="w-full px-4 py-2 border border-gray-300 rounded-md dark:bg-zinc-800 dark:border-zinc-700 font-mono text-sm"
class="w-full rounded-md border border-surface2 bg-surface0 px-4 py-2 font-mono text-sm"
placeholder="Enter post content (HTML)"
/>
</div>
{/* Banner Photo URL */}
<div>
<label for="banner" class="block text-sm font-medium mb-2">
<label for="banner" class="mb-2 block text-sm font-medium">
Banner Photo URL
</label>
<input
@@ -183,26 +183,33 @@ export default function EditPost() {
type="text"
value={bannerPhoto()}
onInput={(e) => setBannerPhoto(e.currentTarget.value)}
class="w-full px-4 py-2 border border-gray-300 rounded-md dark:bg-zinc-800 dark:border-zinc-700"
class="w-full rounded-md border border-surface2 bg-surface0 px-4 py-2"
placeholder="Enter banner photo URL"
/>
</div>
{/* Tags */}
<div>
<label for="tags" class="block text-sm font-medium mb-2">
<label for="tags" class="mb-2 block text-sm font-medium">
Tags (comma-separated)
</label>
<input
id="tags"
type="text"
value={tags().join(", ")}
onInput={(e) => setTags(e.currentTarget.value.split(",").map(t => t.trim()).filter(Boolean))}
class="w-full px-4 py-2 border border-gray-300 rounded-md dark:bg-zinc-800 dark:border-zinc-700"
onInput={(e) =>
setTags(
e.currentTarget.value
.split(",")
.map((t) => t.trim())
.filter(Boolean)
)
}
class="w-full rounded-md border border-surface2 bg-surface0 px-4 py-2"
placeholder="tag1, tag2, tag3"
/>
</div>
{/* Published */}
<div class="flex items-center gap-2">
<input
@@ -216,30 +223,32 @@ export default function EditPost() {
Published
</label>
</div>
{/* Error message */}
<Show when={error()}>
<div class="text-red-500 text-sm">{error()}</div>
<div class="text-red text-sm">{error()}</div>
</Show>
{/* Submit button */}
<div class="flex gap-4">
<button
type="submit"
disabled={loading()}
class={`flex-1 px-6 py-3 rounded-md text-white transition-all ${
class={`flex-1 rounded-md px-6 py-3 text-base transition-all ${
loading()
? "bg-gray-400 cursor-not-allowed"
: "bg-blue-500 hover:bg-blue-600 active:scale-95"
? "bg-blue cursor-not-allowed brightness-50"
: "bg-blue hover:brightness-125 active:scale-95"
}`}
>
{loading() ? "Saving..." : "Save Changes"}
</button>
<button
type="button"
onClick={() => navigate(`/blog/${encodeURIComponent(title())}`)}
class="px-6 py-3 rounded-md border border-gray-300 hover:bg-gray-100 dark:hover:bg-zinc-800 transition-all"
onClick={() =>
navigate(`/blog/${encodeURIComponent(title())}`)
}
class="border-surface2 rounded-md border px-6 py-3 transition-all hover:brightness-125"
>
Cancel
</button>

View File

@@ -11,7 +11,7 @@ import PostSorting from "~/components/blog/PostSorting";
// Server function to fetch posts
const getPosts = cache(async (category: string, privilegeLevel: string) => {
"use server";
let query = `
SELECT
Post.id,
@@ -45,18 +45,19 @@ const getPosts = cache(async (category: string, privilegeLevel: string) => {
}
}
query += ` GROUP BY Post.id, Post.title, Post.subtitle, Post.body, Post.banner_photo, Post.date, Post.published, Post.category, Post.author_id, Post.reads, Post.attachments ORDER BY Post.date DESC;`;
const conn = ConnectionFactory();
const results = await conn.execute(query);
const posts = results.rows;
const postIds = posts.map((post: any) => post.id);
const tagQuery = postIds.length > 0
? `SELECT * FROM Tag WHERE post_id IN (${postIds.join(", ")})`
: "SELECT * FROM Tag WHERE 1=0";
const tagQuery =
postIds.length > 0
? `SELECT * FROM Tag WHERE post_id IN (${postIds.join(", ")})`
: "SELECT * FROM Tag WHERE 1=0";
const tagResults = await conn.execute(tagQuery);
const tags = tagResults.rows;
let tagMap: Record<string, number> = {};
tags.forEach((tag: any) => {
tagMap[tag.value] = (tagMap[tag.value] || 0) + 1;
@@ -67,24 +68,32 @@ const getPosts = cache(async (category: string, privilegeLevel: string) => {
export default function BlogIndex() {
const [searchParams] = useSearchParams();
// TODO: Get actual privilege level from session/auth
const privilegeLevel = "anonymous";
const category = () => searchParams.category || "all";
const sort = () => searchParams.sort || "newest";
const filters = () => searchParams.filter || "";
const data = createAsync(() => getPosts(category(), privilegeLevel));
const bannerImage = () => category() === "project" ? "/blueprint.jpg" : "/manhattan-night-skyline.jpg";
const pageTitle = () => category() === "all" ? "Posts" : category() === "project" ? "Projects" : "Blog";
const bannerImage = () =>
category() === "project"
? "/blueprint.jpg"
: "/manhattan-night-skyline.jpg";
const pageTitle = () =>
category() === "all"
? "Posts"
: category() === "project"
? "Projects"
: "Blog";
return (
<>
<Title>{pageTitle()} | Michael Freno</Title>
<div class="min-h-screen overflow-x-hidden bg-white dark:bg-zinc-900">
<div class="bg-base min-h-screen overflow-x-hidden">
<div class="z-30">
<div class="page-fade-in z-20 mx-auto h-80 sm:h-96 md:h-[30vh]">
<div class="image-overlay fixed h-80 w-full brightness-75 sm:h-96 md:h-[50vh]">
@@ -95,7 +104,7 @@ export default function BlogIndex() {
/>
</div>
<div
class="text-shadow fixed top-36 z-10 w-full select-text text-center tracking-widest text-white brightness-150 sm:top-44 md:top-[20vh]"
class="text-shadow fixed top-36 z-10 w-full text-center tracking-widest text-white brightness-150 select-text sm:top-44 md:top-[20vh]"
style={{ "pointer-events": "none" }}
>
<div class="z-10 text-5xl font-light tracking-widest">
@@ -104,8 +113,8 @@ export default function BlogIndex() {
</div>
</div>
</div>
<div class="relative z-40 mx-auto -mt-16 min-h-screen w-11/12 rounded-t-lg bg-zinc-50 pb-24 pt-8 shadow-2xl dark:bg-zinc-800 sm:-mt-20 md:mt-0 md:w-5/6 lg:w-3/4">
<div class="bg-surface0 relative z-40 mx-auto -mt-16 min-h-screen w-11/12 rounded-t-lg pt-8 pb-24 shadow-2xl sm:-mt-20 md:mt-0 md:w-5/6 lg:w-3/4">
<Suspense
fallback={
<div class="mx-auto pt-48">
@@ -119,8 +128,8 @@ export default function BlogIndex() {
href="/blog?category=all"
class={`rounded border px-4 py-2 transition-all duration-300 ease-out active:scale-90 ${
category() === "all"
? "border-orange-500 bg-orange-400 text-white dark:border-orange-700 dark:bg-orange-700"
: "border-zinc-800 hover:bg-zinc-200 dark:border-white dark:hover:bg-zinc-700"
? "border-peach bg-peach text-base"
: "border-text hover:brightness-125"
}`}
>
All
@@ -129,8 +138,8 @@ export default function BlogIndex() {
href="/blog?category=blog"
class={`rounded border px-4 py-2 transition-all duration-300 ease-out active:scale-90 ${
category() === "blog"
? "border-orange-500 bg-orange-400 text-white dark:border-orange-700 dark:bg-orange-700"
: "border-zinc-800 hover:bg-zinc-200 dark:border-white dark:hover:bg-zinc-700"
? "border-peach bg-peach text-base"
: "border-text hover:brightness-125"
}`}
>
Blog
@@ -139,28 +148,30 @@ export default function BlogIndex() {
href="/blog?category=project"
class={`rounded border px-4 py-2 transition-all duration-300 ease-out active:scale-90 ${
category() === "project"
? "border-blue-500 bg-blue-400 text-white dark:border-blue-700 dark:bg-blue-700"
: "border-zinc-800 hover:bg-zinc-200 dark:border-white dark:hover:bg-zinc-700"
? "border-blue bg-blue text-base"
: "border-text hover:brightness-125"
}`}
>
Projects
</A>
</div>
<PostSortingSelect type={category() === "project" ? "project" : "blog"} />
<PostSortingSelect
type={category() === "project" ? "project" : "blog"}
/>
<Show when={data() && Object.keys(data()!.tagMap).length > 0}>
<TagSelector
tagMap={data()!.tagMap}
category={category() === "project" ? "project" : "blog"}
<TagSelector
tagMap={data()!.tagMap}
category={category() === "project" ? "project" : "blog"}
/>
</Show>
<Show when={privilegeLevel === "admin"}>
<div class="mt-2 flex justify-center md:mt-0 md:justify-end">
<A
href="/blog/create"
class="rounded border border-zinc-800 px-4 py-2 transition-all duration-300 ease-out hover:bg-zinc-200 active:scale-90 dark:border-white dark:hover:bg-zinc-700 md:mr-4"
class="border-text rounded border px-4 py-2 transition-all duration-300 ease-out hover:brightness-125 active:scale-90 md:mr-4"
>
Create Post
</A>
@@ -168,7 +179,7 @@ export default function BlogIndex() {
</Show>
</div>
</Suspense>
<Suspense
fallback={
<div class="mx-auto pt-48">
@@ -178,7 +189,7 @@ export default function BlogIndex() {
>
<Show
when={data() && data()!.posts.length > 0}
fallback={<div class="text-center pt-12">No posts yet!</div>}
fallback={<div class="pt-12 text-center">No posts yet!</div>}
>
<div class="mx-auto flex w-11/12 flex-col pt-8">
<PostSorting