Skip to content

Commit

Permalink
refactor: Add PostData class
Browse files Browse the repository at this point in the history
  • Loading branch information
Hayao0819 committed Jan 9, 2025
1 parent d4265ad commit 3a81021
Show file tree
Hide file tree
Showing 7 changed files with 111 additions and 80 deletions.
42 changes: 17 additions & 25 deletions src/components/layouts/blog/PostPreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
import { motion, Variants } from "framer-motion";

import { Link } from "@/components/elements/Link";
import { PostData } from "@/lib/markdown/post";
import { StaticPostData } from "@/lib/markdown/post";
import * as utils from "@/lib/utils";

const PostPreview = ({ posts }: { posts: PostData }) => {
if (!posts.meta.title || !posts.meta.date) {
const PostPreview = ({ posts: post }: { posts: StaticPostData }) => {
if (!post.meta.title || !post.meta.date) {
return <></>;
}

const postDate = new Date(posts.meta.date);
const postDate = new Date(post.meta.date);

const animate: Variants = {
offscreen: {
Expand All @@ -27,9 +27,7 @@ const PostPreview = ({ posts }: { posts: PostData }) => {
},
};

const contentString = posts.content.replace(/<("[^"]*"|'[^']*'|[^'">])*>/g, "").slice(0, 100) + "...";

const fullURL = "/blog/posts/" + posts.url;
const fullURL = "/blog/posts/" + post.url;
return (
<motion.div
className="border-b p-2"
Expand All @@ -41,20 +39,11 @@ const PostPreview = ({ posts }: { posts: PostData }) => {
<div className="flex h-full flex-col">
<div className="flex justify-between">
<div className="flex justify-start">
{(posts.meta.categories ? posts.meta.categories : ["その他"])
.filter((c) => {
return c !== "ブログ";
})
.map((c) => {
return c ? c : "その他";
})
.map((s) => {
return (
<div className="p-1" key={s}>
<Link href={`/blog/category/${s}`}>{s}</Link>
</div>
);
})}
{post.categories.map((s) => (
<div className="p-1" key={s}>
<Link href={`/blog/category/${s}`}>{s}</Link>
</div>
))}
</div>
<p className="p-1">
<Link className="text-sm" href={`/blog/posts/${utils.dateToString(postDate, "")}`}>
Expand All @@ -64,11 +53,14 @@ const PostPreview = ({ posts }: { posts: PostData }) => {
</div>

<div className="m-2 flex items-center justify-between">
{/* タイトル */}
<Link href={fullURL} className="grow text-xl text-accent underline-offset-8 hover:underline">
{posts.meta.title}
{post.meta.title}
</Link>
<div className="flex">
{posts.meta.tags?.map((s) => {

{/* タグ一覧 */}
<div className="hidden md:flex">
{post.meta.tags?.map((s) => {
return (
<Link href={`/blog/tag/${s}`} className="px-2 text-sm" key={s}>
#{s}
Expand All @@ -80,7 +72,7 @@ const PostPreview = ({ posts }: { posts: PostData }) => {

<div className="m-2 grow">
<Link href={fullURL} className="text-sm">
{contentString}
{post.summary}
</Link>
</div>

Expand Down
2 changes: 1 addition & 1 deletion src/components/layouts/blog/PostPreviewList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function PostList({ posts }: PostListProps) {
return (
<div className="flex flex-col">
{posts.map((f) => {
return <PostPreview posts={f} key={f.file} />;
return <PostPreview posts={f.getStaticData()} key={f.file} />;
})}
</div>
);
Expand Down
4 changes: 2 additions & 2 deletions src/lib/blog/categories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ export type Category = {
export const getAllCategories = () => fetchedBlogPostList.getAllCategories();

export const findCategoryInfo = (category: string): Category | null => {
const catingo = getCategoryInfo();
const matched = catingo.filter((c) => c.url === category || c.jp === category);
const catinfo = getCategoryInfo();
const matched = catinfo.filter((c) => c.url === category || c.jp === category);

if (matched.length === 0) {
return null;
Expand Down
5 changes: 2 additions & 3 deletions src/lib/blog/fromurl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { ReactNode } from "react";
import Markdown from "@/components/elements/Markdown";

import { findMarkdownFromURL } from "../markdown/fromurl";
import { getPostDataFromFile, PostData } from "../markdown/post";
import { PostData } from "../markdown/post";

type FoundPost = {
post?: PostData;
Expand All @@ -16,8 +16,7 @@ export function findPostFromUrl(url: string): FoundPost {
const targetFile = findMarkdownFromURL(path.join(process.cwd(), "posts"), url);

if (targetFile) {
const post = getPostDataFromFile(targetFile);
//console.log(post);
const post = PostData.getFromFile(targetFile);

return {
post: post,
Expand Down
111 changes: 83 additions & 28 deletions src/lib/markdown/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,36 +6,91 @@ import { PostMeta } from "@/lib/markdown/type";
import { BLOG_URL_FORMAT } from "../blog/config";
import { formatURL, mdPathToURL, URLFormat } from "./url";

export function getPostDataFromFile(file: string, urlFormat: URLFormat = BLOG_URL_FORMAT): PostData {
const fileContent = fs.readFileSync(file, "utf-8");
const parsed = matter(fileContent);
const meta: PostMeta = {};

Object.keys(parsed.data).forEach((key) => {
if (key === "date") {
meta[key] = new Date(parsed.data[key]).toISOString();
} else if (key === "categories") {
meta[key] = parsed.data[key].filter((c: string) => c !== "ブログ");
} else {
meta[key] = parsed.data[key];
}
});

//console.log(meta);

const data = {
file: file,
url: formatURL(mdPathToURL(file), urlFormat),
meta: meta,
content: parsed.content,
};

return data;
}

export interface PostData {
export interface StaticPostData {
file: string;
url: string;
meta: PostMeta;
content: string;
summary: string;
categories: string[];
}

export class PostData {
#file: string;
#url: string;
#meta: PostMeta;
#content: string;

get file() {
return this.#file;
}
get url() {
return this.#url;
}
get meta() {
return this.#meta;
}
get content() {
return this.#content;
}

get summary() {
return this.#content.replace(/<("[^"]*"|'[^']*'|[^'">])*>/g, "").slice(0, 100) + "...";
}

get categories() {
return this.#meta.categories
? this.#meta.categories
: ["その他"]
.filter((c) => {
return c !== "ブログ";
})
.map((c) => {
return c ? c : "その他";
});
}

constructor(file: string, url: string, meta: PostMeta, content: string) {
this.#file = file;
this.#url = url;
this.#meta = meta;
this.#content = content;
}

contentSplited(chars: number) {
return new PostData(this.#file, this.#url, this.#meta, this.#content.slice(0, chars));
}

getStaticData(): StaticPostData {
return {
file: this.#file,
url: this.#url,
meta: this.#meta,
content: this.#content,
summary: this.summary,
categories: this.categories,
};
}

static getFromFile(file: string, urlFormat: URLFormat = BLOG_URL_FORMAT): PostData {
const fileContent = fs.readFileSync(file, "utf-8");
const parsed = matter(fileContent);
const meta: PostMeta = {};

Object.keys(parsed.data).forEach((key) => {
if (key === "date") {
meta[key] = new Date(parsed.data[key]).toISOString();
} else if (key === "categories") {
meta[key] = parsed.data[key].filter((c: string) => c !== "ブログ");
} else {
meta[key] = parsed.data[key];
}
});

return new PostData(file, formatURL(mdPathToURL(file), urlFormat), meta, parsed.content);
}

static getFromStaticData(data: StaticPostData, urlFormat: URLFormat = BLOG_URL_FORMAT): PostData {
return new PostData(data.file, formatURL(data.url, urlFormat), data.meta, data.content);
}
}
23 changes: 4 additions & 19 deletions src/lib/markdown/postlist.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import fs from "fs";
import path from "path";

import { getPostDataFromFile, PostData } from "./post";
import { PostData } from "./post";
import { URLFormat } from "./url";

const getMdFilesInDir = (dir: string): string[] => {
Expand All @@ -28,22 +28,15 @@ export class PostList {
this.posts = [];
}

fetch(
dir: string,
format: URLFormat,
//includeDraft: boolean | undefined = undefined,
//includeHidden: boolean | undefined = undefined,
) {
fetch(dir: string, format: URLFormat) {
if (this.fetched) return this;

const files = getMdFilesInDir(dir);
//console.log(getMdFilesInDir(process.cwd()));
//console.log(files);

const posts = files
.map((file) => {
return getPostDataFromFile(file, format);
})
.map((file) => PostData.getFromFile(file, format))
.filter((p) => {
if (p.meta.publish == undefined) return true;
if (p.meta.publish == true) return true;
Expand Down Expand Up @@ -169,15 +162,7 @@ export class PostList {
}

getContentSplitedPosts(perChars: number) {
return PostList.fromPostDatas(
this.posts.map((p) => {
const content = p.content.slice(0, perChars);
return {
...p,
content: content,
};
}),
);
return PostList.fromPostDatas(this.posts.map((p) => p.contentSplited(perChars)));
}

getAllCategories() {
Expand Down
4 changes: 2 additions & 2 deletions src/lib/projects/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import path from "path";
import Markdown from "@/components/elements/Markdown";

import { findMarkdownFromURL } from "../markdown/fromurl";
import { getPostDataFromFile } from "../markdown/post";
import { PostData } from "../markdown/post";
import { PostList } from "../markdown/postlist";

export const projectsDir = path.join(process.cwd(), "src", "app", "(hayao)", "something", "files");
Expand All @@ -19,7 +19,7 @@ export const getProjectFromURL = (url: string) => {
// console.log(mdFile);

if (mdFile) {
const projPost = getPostDataFromFile(mdFile, {
const projPost = PostData.getFromFile(mdFile, {
cutHead: process.cwd().split(path.sep).length + 5,
});
// TODO: basepathがあってるか確認する
Expand Down

0 comments on commit 3a81021

Please sign in to comment.